Java 泛型类
声明语法以及示例
泛型类声明
public class Box<T> {
private T t;
}
- Box :泛型类
- T :类型参数
- t :类型参数T的实例
T是传递给泛型类Box的类型参数,当创建一个Box对象时就要传递了。
Box<类型参数>:类型参数可以有多个,以逗号隔开。
示例
泛型类
public class Box<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
测试类
public class GenericsT {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<>();
Box<String> stringBox = new Box<>();
integerBox.setT(new Integer(100));
stringBox.setT(new String("XiaoYaoZi"));
System.out.println("Integer value: " + integerBox.getT());
System.out.println("String value: "+ stringBox.getT());
Box box = new Box();
box = integerBox;
System.out.println("Box value: " + box.getT());
box.setT(Integer.valueOf(200));
System.out.println("Box value: " + box.getT());
box.setT("xiaoHong");
System.out.println("Box value: " + box.getT());
}
}
Box integerBox = new Box<>(); java程序自动推断后面Box<>的<>中的类型参数。
上面的写法有时候会报错,这并不是代码的问题,而是这种写法需要jdk1.7及以上版本。如果是其下的版本需要更正为:
Box integerBox = new Box();
类型参数命名约定
类型参数名称命名为单个大写字母,以便可以在使用普通类或接口名称时能够容易地区分类型参数。
常用的类型参数名称列表 :
- E - 元素,主要由Java集合(Collections)框架使用。
- K - 键,主要用于表示映射中的键的参数类型。
- V - 值,主要用于表示映射中的值的参数类型。
- N - 数字,主要用于表示数字。
- T - 类型,主要用于表示第一类通用型参数。
- S - 类型,主要用于表示第二类通用类型参数。
- U - 类型,主要用于表示第三类通用类型参数。
- V - 类型,主要用于表示第四个通用类型参数。
public class GenericsTS {
public static void main(String[] args) {
MyBox<Integer, String> integerStringMyBox = new MyBox<>();
integerStringMyBox.setT(new Integer(100));
integerStringMyBox.setS(new String("XiaoYaoZi"));
System.out.println("Integer value: " + integerStringMyBox.getT());
System.out.println("String value: " + integerStringMyBox.getS());
Pair<String, Integer> stringIntegerPair = new Pair<>();
stringIntegerPair.put("key1", new Integer(100));
System.out.println("Pair V: " + stringIntegerPair.getValue("key1"));
CustomList<MyBox> myBoxCustomList = new CustomList<>();
myBoxCustomList.addE(integerStringMyBox);
System.out.println("CustomList MyBox T : " + myBoxCustomList.getE(0).getS());
}
}
//泛型类(多类型参数)
public class MyBox<T, S> {
private T t;
private S s;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public S getS() {
return s;
}
public void setS(S s) {
this.s = s;
}
}
//泛型类(键值对)
public class Pair<K, V> {
private Map<K, V> map = new HashMap<K, V>();
public V getValue(K k) {
return map.get(k);
}
public void put(K k, V v) {
map.put(k, v);
}
}
//泛型类 (Java集合)
public class CustomList<E> {
private List<E> list = new ArrayList<E>();
public void addE(E e) {
list.add(e);
}
public E getE(int index) {
return list.get(index);
}
}