欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

泛型参数

程序员文章站 2022-03-13 12:05:30
...
public class Animal {
	private String id;
	private String name;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

public class Cat extends Animal implements Comparable<Cat>{
	public int compareTo(Cat arg0) {
		return this.getId().compareTo(arg0.getId());
	}

}

 

public class Dog extends Animal implements Comparable<Dog> {
	public int compareTo(Dog arg0) {
		return this.getId().compareTo(arg0.getId());
	}
}

 

public  class demo<E> 
{
	List rsList=new ArrayList();
	public E getById(E o)
	{
		System.out.println(o);
		return o ;
	}
}

 

public class Demo1 {
	public <E extends Animal>void getByid(List<E> e)
	{     		
	}
	public void getByidL(List<Animal> list)
	{	
	}
}

 

public class DemoTest {
	public static void main(String[] args) {
		
		System.out.println("***********");
		demo<String> demo=new demo<String>();
		demo.getById("ddddd");
	}
	public void test()
	{
		List<Dog> list=new ArrayList<Dog>();
		List<Animal>list1=new ArrayList<Animal>();
		Demo1 demo=new Demo1();
		demo.getByidL(list1);//只能是Animal
		demo.getByid(list);//可以使Animal或它的继承类或实现类 
		demo.getByid(list1);
//		demo.getByidL(list);//this is wrong because List<Dog> is not List<Animal>
		
	}
	/**
	 * 创建内部类来依据name来排序
	 * @author wei
	 *
	 */
	class NameCompare implements Comparator<Cat>
	{
		public int compare(Cat arg0, Cat arg1) {
			return arg0.getName().compareTo(arg1.getName());
		}
	}
	/**
	 * 创建的内部类来依据id来排序
	 * @author wei
	 *
	 */
	class IdCompare implements Comparator<Cat>
	{
		public int compare(Cat arg0, Cat arg1) {
			return arg0.getId().compareTo(arg1.getId());
		}
	}
public void test1()
{
	List<Cat>rslist=new ArrayList<Cat>();
	NameCompare nameCompare=new NameCompare();
    Collections.sort(rslist, nameCompare);//调用了
}
}

 

相关标签: 泛型