java中的Set集合HashSet集合

 时间:2024-11-06 16:46:50

1、public class HashSetDemo { public static void main(String[] args) { //创建集合 HashSet<Student> hash = new HashSet<Student>(); //创建学生对对象 Student s1 = new Student("one",1); Student s2 = new Student("two",2); Student s3 = new Student("two",2); Student s4 = new Student("three",3); Student s5 = new Student("four",4); Student s6 = new Student("four",4); Student s7 = new Student("five",5); //添加 hash.add(s1); hash.add(s2); hash.add(s3); hash.add(s4); hash.add(s5); hash.add(s6); hash.add(s7); //遍历 for(Student s : hash) { System.out.println(s.getAge() + s.getName()); //不是说唯一性吗?为什么打印出来发现相同的元素还是有的呢? //原因是因为低沉用hashcode和equals方法进行比较的 //而对象却没有重写父类Object的hashcode和equals方法!所以当然不同了! } }}

2、所以在学生对象要重写equals和Hashcode方法:@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { 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; return true; }

3、打印输出:3three4four1one2two5five可见唯一!

  • 如何在Android Studio中添加多个项目
  • pycharm2019激活方法
  • windows10安装vscode教程
  • QT Creator原创详细安装指导
  • .net数据库的帮助操作类DBHelper--youchim
  • 热门搜索
    勤俭节约手抄报图片 向国旗敬礼手抄报图 阳光心理手抄报 放飞心灵手抄报内容 环保手抄报资料大全 科技之光手抄报 元旦节手抄报图片 防地震手抄报内容 护林防火手抄报 三年级春节手抄报大全