本帖最后由 张洪慊 于 2013-4-14 01:06 编辑
- package test;
- import java.util.*;
- class Animal{
- private String name;
- Animal(String name){
-
- this.name=name;
-
- }
- public String getName(){
-
- return name;
-
- }
- }
- class Pig extends Animal{
- Pig(String name){
- super(name);
- }
- }
- class Bird extends Animal{
- Bird(String name){
-
- super(name);
-
- }
- }
- class Demo{
-
- public static void main(String[] args){
-
- TreeSet<Pig>ts1 = new TreeSet<Pig>(new Com());
- ts1.add(new Pig("P1"));
- ts1.add(new Pig("P2"));
-
- TreeSet<Bird>ts2 = new TreeSet<Bird>(new Com());
- ts2.add(new Bird("B1"));
- ts2.add(new Bird("B2"));
- method(ts1);
- method(ts2);
-
-
- }
- /*
- 构造函数:
- TreeSet(Comparator<? super E> comparator)
- 例如:E为Pig
- TreeSet(Comparator<? super Pig> comparator)
- 对于以上其可传入类型为:Comparator<Pig>或Comparator<Animal>或Comparator<Object>
- 当传入Comparator<? super Pig>=new Com()时,new Com()为原始类型的对象,为什么不会发出警告?
- */
- public static <T extends Animal> void method(TreeSet<T> ts ){
-
- for(Iterator<T>it=ts.iterator();it.hasNext();){
-
- System.out.println(it.next().getName());
- }
- }
- }
- class Com implements Comparator<Animal>{
- public int compare(Animal a1,Animal a2){
-
- return a1.getName().compareTo(a2.getName());
-
- }
-
- }
复制代码 为此写个小程序 模拟下:- class Father<T>{
- T str;
- }
- class Son extends Father<Integer>{//传递一个实参Integer
- //为了测试
- public void method(Father<String> t){
- System.out.println(str);
- }
-
- public static void main(String[] args){
- new Son().method(new Father<String>());//可以Father<String> t=new Father<String>();
- new Son().method(new Son());//编译失败,无法Son 转换成 Father<String>(无法通过方法调用转换将实际参数Son转换为Father<String>)
- //(Father)new Son() ->强制类型提升->仅仅发出警告,为什么?
- }
- }
复制代码 对以上略作修改:- class Father<T>{
- T str;
- }
- class Son extends Father<String>{//改为<String>
- //为了测试
- public void method(Father<String> t){
- System.out.println(str);
- }
-
- public static void main(String[] args){
- new Son().method(new Father<String>());//可以Father<String> t=new Father<String>();
- new Son().method(new Son());//正常,没有警告, Father<String> t =new Son( ),为什么不会发出警告呢?和Comparator例子很类似.
- //如果在这里也强制类型提升(Father)new Son()->编译会发出警告
- }
- }
复制代码 希望能够针对以上例子,详细分析下.
|