Set是唯一 无序的

来源:互联网 发布:淘宝幸运大抽奖在哪 编辑:程序博客网 时间:2024/04/27 17:22

在Set插入自定义类,通过new的对象地址值不同,但是数值可能相同,为了保证set的唯一性特点,要重写hashcode()和equals()方法

@Override
    public int hashCode() {                                                     //重写hashCode()方法
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(score);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + sid;
        return result;
    }

    @Override
    public boolean equals(Object obj) {                                 //重写equals()方法
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(score) != Double
                .doubleToLongBits(other.score))
            return false;
        if (sid != other.sid)
            return false;
        return true;
    }
public class TestHashSet2 {
    public static void main(String[] args) {
        
        //1.创建集合对象
//        HashSet<Student> setStu=new HashSet<Student>();
//        
        Set<Student> setStu=new LinkedHashSet<Student>();
        //2.添加学员信息
        
        
        setStu.add(new Student(1001,"aa",12,78.9));           //相同的对象
        setStu.add(new Student(1002,"bb",23,89));
        setStu.add(new Student(1003,"cc",18,100));
        setStu.add(new Student(1001,"aa",12,78.9));          //相同的对象

        setStu.add(new Student(1001,"aa",12,78.9));          //相同的对象   
        //3.遍历输出
        System.out.println(setStu.size());                                    //输出为     3                      若不重写hashcode()和equals()方法
输出为   5
        System.out.println(setStu.toString());
        
        
    }
}



0 0