自定义类型对象存入HashSet集合的过程 您所在的位置:网站首页 创建一个集合用于存放对象 自定义类型对象存入HashSet集合的过程

自定义类型对象存入HashSet集合的过程

2024-05-30 21:45| 来源: 网络整理| 查看: 265

将字符串存入HashSet时,String类就已经默认重写了hashCode()和equals()方法,如果将自定义类型对象存入HashSet集合,结果如何?

package com.sgl; import java.util.HashSet; class Student{ String id; String name; public Student(String id,String name) { this.id = id; this.name = name; } @Override public String toString() { return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } } public class Test { public static void main(String[] args) { HashSet hashSet = new HashSet(); Student stu1 = new Student("001","施刚龙"); Student stu2 = new Student("003","Rose"); Student stu3 = new Student("003","Rose"); hashSet.add(stu1); hashSet.add(stu2); hashSet.add(stu3); System.out.println(hashSet); } }

运行结果:

[Student{id='003', name='Rose'}, Student{id='001', name='施刚龙'}, Student{id='003', name='Rose'}]

简述:向HashSet集合存入三个Student对象,打印结果出现了两个Student{id=‘003’, name=‘Rose’},这样的学生信息应该被视为重复元素,不允许出现在HashSet集合中。原因是在定义Student类时没有重写hashCode()和equals()方法,因此创建的这两个学生对象的地址不同,所以HashSet集合会认为这是两个不同的元素。

解决方法:Student类进行改写,增加重写hashCode()和equals()方法,假设id相同的学生就是同一个学生,如下代码:

package com.sgl; import java.util.HashSet; class Student{ String id; String name; public Student(String id,String name) { this.id = id; this.name = name; } @Override public String toString() { return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + '}'; } @Override public int hashCode() { //return super.hashCode(); //没有重写之前 return id.hashCode(); //返回id属性的哈希值 } @Override public boolean equals(Object obj) { //return super.equals(obj); //没有重写之前 if (this==obj){ //判断是否是同一个对象 return true; //如果是直接返回true } if (!(obj instanceof Student)) { //判断对象是否为Student类型 return false; //如果是直接返回false } Student stu = (Student) obj; //将对象转换为Student类型 boolean b = this.id.equals(stu.id); //判断id是否相同 return b; //返回判断结果 } } public class Test { public static void main(String[] args) { HashSet hashSet = new HashSet(); Student stu1 = new Student("001","施刚龙"); Student stu2 = new Student("003","Rose"); Student stu3 = new Student("003","Rose"); hashSet.add(stu1); hashSet.add(stu2); hashSet.add(stu3); System.out.println(hashSet); } }

运行结果:

[Student{id='001', name='施刚龙'}, Student{id='003', name='Rose'}]

简述:

Student类重写了Object类的hashCode()方法和equals()方法。在hashCode()方法返回id属性的哈希值,在equals()方法中比较对象的id是否相等,并返回结果。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有