汎用パラメータ
2642 ワード
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);//
}
}