關於集合的使用

1.初始化一個list集合eclipse

 List<Student> list=new LinkedList<Student>();

這個時候須要注意的是當咱們用myeclipse時導入包應該要導正確。ide

2.向list當中添加對應的類對象元素this

list.add(new Student("1","zhangsan",20));
         list.add(new Student("2","lisi",19));
         list.add(new Student("3","wangwu",18));

3.咱們須要對集合中的元素進行排序操做的時候,須要用到collection類進行操做spa

Collections.sort(list);    

此時須要注意的是咱們要對類對象進行排序的時候須要實現Comparable<Student>接口code

public class Student implements Comparable<Student> {
    private String Id;
    private String name;
    private int age;
    public Student(String id, String name, int age) {
        super();
        Id = id;
        this.name = name;
        this.age = age;
    }
    public String getId() {
        return Id;
    }
    public void setId(String id) {
        Id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
     @Override  
     public int compareTo(Student stu) {  
        if(this.getAge()>stu.getAge()){
            return 1;
        }else if(this.getAge()==stu.getAge()){
            return 0;
        }else{
            return -1;
        }
          
        }  

}
View Code

4.完成後就能夠用foeach語句對集合內的元素進行迭代遍歷對象

 for(Student e:list){
             System.out.println(e.getId()+" "+e.getName()+" "+e.getAge());
         }
相關文章
相關標籤/搜索