黑马程序员技术交流社区
标题:
泛型限定问题!
[打印本页]
作者:
ò壞尛孩
时间:
2014-4-22 15:46
标题:
泛型限定问题!
最近看到泛型的视频,有点点的小疑惑!泛型在C++里面 有点类似STL模板 不过C++里面是用Template关键字定义的
写法上没有JAVA的<>方便
package liang;
import java.util.*;
class Person1
{
private String name;
private int age;
Person1(String name,int age)
{
this.name=name;
this.age=age;
}
/* public int compareTo(Object obj)
{
if(!(obj instanceof Person))
throw new RuntimeException("参数不正确");
Person p=(Person)obj;
if(this.age>p.age)return 1;
if(this.age==p.age)
return this.name.compareTo(p.name);
return -1;
}*/
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public void show()
{
System.out.println(this.name+"..."+this.age);
}
}
class Student1 extends Person1
{
Student1(String name,int age)
{
super(name,age);
}
}
class Comp implements Comparator<Person1>
{
public int compare(Person1 a,Person1 b)
{
return a.getName().compareTo(b.getName());
}
}
class GenericDemo
{
public static void main(String[] args)
{
TreeSet<Student1>s=new TreeSet<Student1>(new Comp());
s.add(new Student1("lisi00",21));
s.add(new Student1("lisi01",21));
s.add(new Student1("lisi02",21));
s.add(new Student1("lisi03",21));
Iterator<Student1> it =s.iterator();
while(it.hasNext())
{
it.next().show();
}
}
}
复制代码
毕老师说泛型限定分上限和下限
<? extends E>是上限,也就是可是接收E和E的子类类型
<? super E>是下限,也就是可是接受E和E的父类类型
TreeSet
(
Comparator
<? super
E
> comparator)
构造一个新的空 TreeSet,它根据指定比较器进行排序。
这不是泛型下限吗?Student继承Person,程序中Comparator比较器中传入的是Person类,应该是只能接受Person类和它的父类啊!为啥子类Student可以传
谁可以给我解释下这个extends和super上下限!
作者:
osully
时间:
2014-4-22 20:30
哥们 你确实很细心 发现这么多
不过这个很好理解
对应TreeSet<E>
Comparetor<T>
TreeSet(Comparator<? super E> comparator)
也就是T 是那个问号 比较器传入的类型当然要是存入TreeSet中的父类才可以
作者:
ò壞尛孩
时间:
2014-4-23 14:48
osully 发表于 2014-4-22 20:30
哥们 你确实很细心 发现这么多
不过这个很好理解
谢谢大神解释!我懂了!
也就是 这个比较器Comparetor(T) 传入的类型 必须是 数据类型TreeSet(E)的父类或者自己的类型!而不是说只接受T和T的父类型是吧!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2