泛型的定义:
<T>
泛型的作用:
1.限定具体类型,确保类型一致,避免类型转换异常
2.不指定具体类型,提高功能的复用性
泛型---定义在类上
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
//1.按姓名比较
int comp = o1.getName().compareTo(o2.getName());
//2.姓名相同,则继续按年龄比较,否则按姓名排序
return comp==0?(o1.getAge()-o2.getAge()):comp;
}
}
泛型---定义在方法上
public static void main(String[] args) {
show(1);
show("abc");
Person p = new Person("zs");
show(p);
}
public static <T> void show(T t) {
System.out.println(t);
}
泛型---通配符 ?
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
iterColletion(list);
Set<String> set = new TreeSet<String>();
set.add("a");
set.add("b");
iterColletion(set);
}
/**
* 泛型通配符 ?
* 当类型不确定时/无法指定具体类型/需要类型复用时,使用通配符
* @param coll
*/
public static void iterColletion(Collection<?> coll) {
Iterator<?> iter = coll.iterator();
while(iter.hasNext())
System.out.println(iter.next());
}
泛型---限定上限
public static void main(String[] args) {
List<Student> stuList = new ArrayList<Student>();
stuList.add(new Student("zs"));
iterColletion(stuList);
Set<Teacher> teacSet = new HashSet<Teacher>();
teacSet.add(new Teacher("ls"));
iterColletion(teacSet);
}
/**
* 泛型-限定上限 ? extends E
* 只接收指定E类型及其子类型,这样就可以在迭代集合时使用父类中的方法了。
* @param coll
*/
public static void iterColletion(Collection<? extends Person> coll) {
Iterator<? extends Person> iter = coll.iterator();
while(iter.hasNext()) {
Person p = iter.next();
System.out.println(p.getName()+":"+p.getAge());
}
}