?通配符,也可以理解为占位符
一、printColl(ArrayList al)只能打印String类型的对象
public static void printColl(ArrayList<String> al) {
Iterator it=al.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
public static void main(String[] args) {
ArrayList<String> al=new ArrayList<String>();
al.add("abc1");
al.add("abc2");
al.add("abc2");
ArrayList<Integer> al1=new ArrayList<Integer>();
al1.add(4);
al1.add(7);
al1.add(5);
//printColl(al1);//编译不能通过,相当于ArrayList<String> al=new ArrayList<Integer>();两边的类型不匹配
所以printColl方法只能接收String类型的元素,而不能接收其他类型的元素
}
}
二、想要解决一中的不能打印任意类型元素的问题的做法是:
public static void printColl(ArrayList<?> al) {
Iterator<?> it=al.iterator();//迭代器也是任意类型
while(it.hasNext()) {
System.out.println(it.next());
}
}
三、public static void printColl(ArrayList al)
ArrayList al=new ArrayList();在这种具体引用类型中,两端的引用类型必须相同,*否则编译失败*
//代码功能说明:父类(people)、子类(student),想通过继承输出所有的子父类元素,这是不可以的!!!!
public class People {
private String name;
People(String name){
this.name=name;
}
public String getName() {
return name;
}
}
public class Student extends People {
Student (String name){
super(name);
}
}
public class Demo {
public static void main(String[] args) {
ArrayList<People> al=new ArrayList<People>();
al.add(new People("abc1"));
al.add(new People("abc2"));
al.add(new People("abc3"));
ArrayList<Student> all=new ArrayList<Student>();
all.add(new Student("abc--1"));
all.add(new Student("abc--2"));
all.add(new Student("abc--3"));
//printColl(all);ArrayList<People> al=new ArrayList<Student>();编译失败,
//记住若是具体引用类型,则左右要一致。(除了?通配符存在子父类关系)
}
public static void printColl(ArrayList<People> al) //ArrayList<People> al=new ArrayList<Student>();
{
Iterator<People> it=al.iterator();
while(it.hasNext()) {
System.out.println(it.next().getName());
}
}
}
四、依据三,存在输出问题,若想要解决,就用到了‘’?‘’,
泛型而定限定:? extends E:可以接收E类型或者E 的子类型(上限)
? super E:可以接收E类型或者E 的父类型(下限)
这样就可以接收people和people的子类了,进而进行打印了
public static void printColl(ArrayList<? extends People > al)
{
Iterator<? extends People > it=al.iterator();
while(it.hasNext()) {
System.out.println(it.next().getName());
}
}
public class People {
private String name;
People(String name){
this.name=name;
}
public String getName() {
return name;
}
}
public class Student extends People {
public Student (String name){
super(name);
}
}
public class Comp implements Comparator<People>//实现的比较器是父类型的
{
public int compare(People p1,People p2) {
int num=p1.getName().compareTo(p2.getName());
if(num==0) {
return p1.getName().compareTo(p2.getName());
}
return num;
}
}
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeSet<Student> ts=new TreeSet<Student>(new Comp());//子类型可以使用这个比较器
ts.add(new Student("abc22"));
ts.add(new Student("abc29"));
ts.add(new Student("abc22"));
Iterator<Student> it=ts.iterator();
while(it.hasNext()) {
System.out.println(it.next().getName());
}
}
}