Java泛型通配符用于表示未知类型。在泛型类、接口和方法中使用通配符可以使其具有更大的灵活性。
通配符有三种使用方式:
- 上界通配符(? extends 类型):表示接受类型参数为类型或其子类的对象。
public void printList(List extends Number> list) { for (Number n : list) { System.out.println(n); } }
在这个例子中,printList方法接受一个参数为类型参数为Number或其子类的List对象。可以传入List
- 下界通配符(? super 类型):表示接受类型参数为类型或其父类的对象。
public void addToList(List super Integer> list) { list.add(1); list.add(2); }
在这个例子中,addToList方法接受一个参数为类型参数为Integer或其父类的List对象。可以传入List
- 无界通配符(?):表示接受任意类型参数的对象。
public void printList(List> list) { for (Object obj : list) { System.out.println(obj); } }
在这个例子中,printList方法接受一个参数为任意类型参数的List对象。可以传入List
需要注意的是,使用通配符时不能进行具体的类型操作,只能进行类型的读取或写入操作。