文章目录
泛型
泛型的使用:
- jdk1.5新特性
- 在集合中使用泛型:
在接口或集合类在jdk5.0都修改为带泛型的结构
在实例化集合类时,可以指明具体的泛型类型
指明完以后,在集合类或接口中凡是定义类或接口时,内部结构使用到类的泛型的位置,都指定为实例化的泛型类型、 - 泛型的类型必须是类,不能是基本数据类类型,需要用到基本数据类型的位置,拿包装类替换
- 如果实例化时没有指明泛型的类型,默认类型为Object
静态方法不能使用泛型结构
泛型方法与泛型类没有关系
泛型在继承方面的体现:
* 虽然类A是类B的父类,但是G<A> 和 G<B> 二者是并列关系,A<G>是B<G>的父类
* 通配符的使用:<?>
* G<A>和G<B>的共同父类是G<?>
public void test(){
ArrayList<Integer> arrayList = new ArrayList<>(); //根据类型推断,后面的<>中不需要写类型
arrayList.add(12);
arrayList.add(345);
arrayList.add(4332);
for (int i : arrayList){
System.out.println(i);
}
Map<String, Integer> map = new HashMap<>();
map.put("we", 12);
map.put("as", 34);
map.put("qw", 45);
map.put("er", 32);
//泛型的嵌套
Set<Map.Entry<String, Integer>> entries = map.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entries.iterator();
while (iterator.hasNext()){
Map.Entry<String, Integer> e = iterator.next();
String key = e.getKey();
Integer value = e.getValue();
System.out.println(key + "," + value);
}
}
自定义泛型类:
public class Person<T> {
private String name;
private int age;
T personT;
public Person() {
}
public Person(String name, int age, T personT) {
this.name = name;
this.age = age;
this.personT = personT;
}
public T getPersonT() {
return personT;
}
//静态方法不能使用泛型结构
/*public static void show(T personT){}*/
}
class Teacher extends Person<String>{ //Teacher类不是泛型类
//自定义泛型方法:
public <E> List<E> copyArrayList(E[] e){
ArrayList<E> arrayList = new ArrayList();
for (E e1 : e){
arrayList.add(e1);
}
return arrayList;
}
public static void main(String[] args) {
Teacher teacher = new Teacher();
Integer[] integers = new Integer[]{11,22,33,44};
List<Integer> integers1 = teacher.copyArrayList(integers);
System.out.println(integers1);
}
}
class Student<T> extends Person<T>{ //Student类仍然是泛型类
}
带限制条件的通配符的使用
public void test(){
List<? extends Person> list1 = null;
List<? super Person> list2 = null;
List<Student> list3 = null;
List<Person> list4 = null;
List<Object> list5 = null;
list1 = list3;
list1 = list4;
// list1 = list5; 编译错误
// list2 = list3; 编译错误
list2 = list4;
list2 = list5;
}