首页 > 代码库 > 泛型例子

泛型例子

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Text3 {
    public static void main(){
         List<String> list= new ArrayList<String>();
         List<Person2> list2= new ArrayList<Person2>();
         List<Student> list3= new ArrayList<Student>();
         list2.add(new Person2());
         
         Set<String> set=new HashSet<String>();
         //不能出现基础数据类型,用包装类
         Map<Integer,String> map= new HashMap<Integer,String>();
         
         map.put(3, "aa");
         list.add("qqq");
    }
}
class Person2{
    
}
class Student extends Person2{
    
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Text4 {
     public static void main(String[] args){
         List<Animals> list=new ArrayList<Animals>();
         
         for(int i=0;i<5;i++){
             list.add(new Animals("name"+i,i+5));
         }
         System.out.println(list);
         Collections.sort(list);
         System.out.println(list);
     } 
}
class Animals implements Comparable<Animals>{
    private String name;
    private int age;
    
    public Animals(String name,int age){
        super();
        this.name=name;
        this.age=age;
    }

    @Override
    public int compareTo(Animals o) {
        if(this.age>o.age){
            return 1;
        }else if(this.age<o.age){
            return -1;
        }else{
            return this.name.compareTo(o.name);
        }
        
    }

    @Override
    public String toString() {
        return "Animals [name=" + name + ", age=" + age + "]";
    }
    
}

 

泛型例子