Set List 都继承Collection

Collection:元素之间没有顺序,允许重复和多个null元素对象。

Set:元素之间没有顺序,不允许重复只能存一个null。

List:元素之间有顺序,允许重复和多个null元素对象。

由于Set Collection没有顺序所以没有按索引取存改等方法,如get(index);所以用for循环遍历时只能用加强for遍历

Class TestCollection {
    public static void mian(String[] args){
        Set<Student> set = new HashSet();
        Student s1 = new Student("s1",20);
        set.add(s1);     //Set只能存一个 因为返回的equals函数和hashCode()的值都一样
        set.add(s1);
        set.add(new Student("s2",21));//当没有重写equals和hashCode函数时可以存两个
        set.add(new Stuent("s2",21));
        for(Student s:set){           //增强for 一般用于遍历 不能对元素进行操作 所以一般用迭代器
            System.out.println(s);
        }
    }
}

Class Student {
    private int age;
    private String name;
    public Student (int age,String name) {
       super();
       this.name = name;
       this.age = age;
    }
    public String toString(){
        return "Student [ age= "+age+"name="+name+"]";
    }
    public boolean equals(Student s) {
        if(name.equals(s.name)&&age.equals(s.age))return true;
    }
    public int hashCode() {
       return name.hashCode()+age;
    }
}
                    

Collection Set List   集合二

相关文章:

  • 2022-01-14
  • 2021-12-23
  • 2021-05-03
  • 2021-06-02
  • 2021-09-05
  • 2021-06-09
  • 2021-10-12
猜你喜欢
  • 2021-11-17
  • 2021-06-09
  • 2022-12-23
  • 2021-09-23
  • 2021-09-29
  • 2021-05-22
  • 2021-10-15
相关资源
相似解决方案