java===泛型

package 泛型;

import java.util.ArrayList;
import java.util.Iterator;

public class GenericDemo {

    public static void main(String[] args) {
        ArrayList<String> a1 = new ArrayList<String>();
        a1.add("乔丹");
        a1.add("科比");
        a1.add("奥尼尔");
        a1.add("詹姆斯");
        Iterator<String> it = a1.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }

    }

}
package 泛型;

import java.util.Iterator;
import java.util.TreeSet;

import 对象库.Person;
import 比较器.comparator.ComparetorByAge;

public class GenericDemo2 {

    public static void main(String[] args) {
        TreeSet<Person> t1 = new TreeSet<Person>(new ComparetorByAge());
        t1.add(new Person("刘德华",50));
        t1.add(new Person("梁朝伟",38));
        t1.add(new Person("周华健",45));
        t1.add(new Person("苏有朋",37));
        t1.add(new Person("王宝强",39));
        Iterator<Person> it = t1.iterator();
        while(it.hasNext()){
            Person p1 = it.next();
            System.out.println(p1.getName()+":"+p1.getAge());
        }

    }

}
package 泛型;

import 对象库.Person;

public class GenericDemo3 {

    public static void main(String[] args) {
        Tool<Person> t1 = new Tool<Person>();
        t1.setObject(new Person("Mr.tom", 23));
        Person p1=t1.getObject();
        System.out.println(p1.getName()+":"+p1.getAge());
        
        

    }

}
package 泛型;

public class GenericDemo4 {

    public static void main(String[] args) {
        InterImpl<Integer> i1 = new InterImpl<Integer>();
        i1.show(5);

    }

}
//泛型接口
interface Inter<T>{
    public void show(T t);
}
class InterImpl<Q> implements Inter<Q>{
    public void show(Q q){
        System.out.println(q);
    }
}
package 泛型;



public class Tool <T>{
    private T t;
    public void setObject(T t){
        this.t=t;
    }
    public T getObject(){
        return t;
    }
    //泛型定义在方法
    //如果方法被static修饰,不能访问类上定义的泛型。只能将泛型定义在方法上;
    public <W> void show(W w){
        System.out.println(w);
    }
    public void print(T t){
        System.out.println(t);
    }
    public static <Y> void method(Y y){
        System.out.println("method:"+y);
    }
}
原文地址:https://www.cnblogs.com/wangyinxu/p/6738048.html