简单的自定义泛型类
程序员文章站
2022-05-23 14:18:35
...
1.自定义泛型类可以先定义一个正常的实体类,里面有对应的属性和方法,例如:
package com;
import java.util.ArrayList;
import java.util.List;
public class order {
private String orderName;
private int orderId;
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
@Override
public String toString() {
return "order [orderId=" + orderId + ", orderName=" + orderName + "]";
}
}
2.然后在属性中加入你想要加入的属性,并在类声明的地方加入有泛型的声明,例如:
package com;
import java.util.ArrayList;
import java.util.List;
//自定义泛型类
public class order<T> {
private String orderName;
private int orderId;
private T t;
List<T> list = new ArrayList<T>();
public void add(){
list.add(t);
}
public T getT(){
return t;
}
public void setT(T t){
this.t = t;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
@Override
public String toString() {
return "order [orderId=" + orderId + ", orderName=" + orderName
+ ", t=" + t + "]";
}
}
3.关于泛型的使用,可以使用下面的方法:
package com;
import java.util.List;
//自定义泛型类的使用
public class testOrder {
public static void main(String[] args) {
order<Boolean> Order = new order<Boolean>();
Order.setT(true);
System.out.println(Order.getT()+"===OTHER==="+Order.getOrderName());
Order.add();
Order.add();
Order.add();
List<Boolean> list = Order.list;
System.out.println(list);
System.out.println(Order.toString());
}
}
4.控制台的输出为:
true===OTHER===null
[true, true, true]
order [orderId=0, orderName=null, t=true]
5.如果比较复杂的,例如多参的
package com;
public class Pair<T> {
private T first;
private T last;
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public T getLast() {
return last;
}
public void setLast(T last) {
this.last = last;
}
public Pair(T first, T last) {
super();
this.first = first;
this.last = last;
}
}
6.一些疑问
7.当然泛型还可以定义多种类型
例如:
package com;
public class Pair<T,K> {
private T first;
private K last;
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public K getLast() {
return last;
}
public void setLast(K last) {
this.last = last;
}
public Pair(T first, K last) {
super();
this.first = first;
this.last = last;
}
}
上一篇: 初探Tomcat的架构设计