问题:

package day30_HashSet;

import java.util.HashSet;

/*
* 通过hashset存储自定义对象,没有进行去重。
*
* */
public class HashSetSutdentDemo { public static void main(String[] args) {
//创建集合对象
HashSet<Student> hs = new HashSet<Student>(); //创建元素对象
Student st = new Student("aa",20);
Student st2 = new Student("bb",18);
Student st3 = new Student("bb",18);
//添加元素对象
hs.add(st);
hs.add(st2);
hs.add(st3); //遍历集合对象
for (Student s : hs) {
System.out.println(s);
} }
} class Student {
String name;
int age; public Student(String name,int age) {
this.name = name;
this.age = age;
} @Override
public String toString() { //默认输出的是student的地址值,重写tostring方法
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

输出

解决:

HashSet 的 add方法使用的是 hashcode 和equals进行比较

需要重写hashcode 和equals

package day30_HashSet;

import java.util.HashSet;
import java.util.Objects; /*
* 使用HashSet存储自定义对象并遍历
* 通过查看源码发现:
* HashSet的add()方法,首先会使用当前集合中的每一个元素和新添加的元素进行hash值比较,
* 如果hash值不一样,则直接添加新的元素
* 如果hash值一样,比较地址值或者使用equals方法进行比较
* 比较结果一样,则认为是重复不添加
* 所有的比较结果都不一样则添加 */
public class HashSetStudentDemo2 {
public static void main(String[] args) {
HashSet<Student2> hs = new HashSet<Student2>();
//创建元素对象
Student2 s = new Student2("zhangsan",18);
Student2 s2 = new Student2("lisi",19);
Student2 s3 = new Student2("lisi",19);
//添加元素对象
hs.add(s);
hs.add(s2);
hs.add(s3);
//遍历集合对象
for (Student2 student : hs) {
System.out.println(student);
}
}
} class Student2 {
String name;
int age; public Student2(String name,int age) {
this.name = name;
this.age = age;
} @Override
public String toString() {
return "Student2{" +
"name='" + name + '\'' +
", age=" + age +
'}';
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student2 student2 = (Student2) o;
return age == student2.age &&
Objects.equals(name, student2.name);
} @Override
public int hashCode() { return Objects.hash(name, age);
}
}

最新文章

  1. Python爬虫 网页图片
  2. MVVM: 通过 x:Bind 实现 MVVM(不用 Command)
  3. 如何将扩展名为.backup的文件导入postgresql中 求步骤 新手 谢谢.
  4. unicode转码,如:\u6d4b\u8bd5转成中文“测试”
  5. Making your local server accessible from anywhere
  6. 移動電源ic的概述
  7. 【Hadoop】 2.7.3版本 hdfs 命令行使用
  8. Vue入门手册整理
  9. ESXI 6.5安装详细步骤
  10. RSA 格式 - 转载
  11. Deloyment Descriptor web.xml
  12. Qt编写自定义控件5-柱状温度计
  13. R 语言 Windows 环境 安装与Windows下制作R的package--Rtools
  14. sql_id VS hash_value
  15. C# 多线程并发锁模式-总结
  16. Xcode搭建Python编译环境
  17. 微信小程序开发教程(六)配置——app.json、page.json详解
  18. html中切记ID不能重复
  19. Activiti初学者教程 (zhuan)
  20. 【Linux】结合Python 简易实现监控公司网站,邮件发送异常

热门文章

  1. fatal: I don&#39;t handle protocol &#39;git@http&#39; 解决
  2. vue 模板 template init
  3. Python基础篇(五)_文件和数据格式化
  4. Natas31 Writeup(Perl 远程命令执行)
  5. jquery 获取url携带的参数
  6. 原创 记录一次线上Mysql慢查询问题排查过程
  7. Python异常处理,将异常写入到一个文件
  8. Hive架构原理
  9. Thinking in Java学习杂记(5-6章)
  10. PYTHON数据类型(基础)