大家好,又见面了,我是你们的朋友全栈君。
上次说了List集合的去重,这次来说说Set集合的去重
public static void main(String[] args) {
HashSet hs=new HashSet<>();
hs.add("a");
hs.add("b");
hs.add("c");
hs.add("a");
hs.add("a");
for (Object obj : hs) {
System.out.println(obj);
}
}
从中可以看出HashSet中是有去重功能的,那我们来试试自定义对象,看看能不能去重。
package com.liang.set;
import java.util.HashSet;
public class SetRemo {
public static void main(String[] args) {
HashSet hs=new HashSet<>();
hs.add(new Student("a","12"));
hs.add(new Student("b", "12"));
hs.add(new Student("c", "13"));
hs.add(new Student("c","12"));
hs.add(new Student("a","12"));
for (Object obj : hs) {
if(obj instanceof Student) {
Student stu=(Student)obj;
System.out.println(stu.getName()+stu.getAge());
}
}
}
}
class Student{
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public Student() {
}
}
结果如下
HashSet元素是自定义对象时,它的去重功能失效了,那怎么才能实现去重呢?
下面让我们来看看代码该怎么写
package com.liang.set;
import java.util.HashSet;
public class SetRemo {
public static void main(String[] args) {
HashSet hs=new HashSet<>();
hs.add(new Student("a","12"));
hs.add(new Student("b", "12"));
hs.add(new Student("c", "13"));
hs.add(new Student("c","12"));
hs.add(new Student("a","12"));
for (Object obj : hs) {
if(obj instanceof Student) {
Student stu=(Student)obj;
System.out.println(stu.getName()+stu.getAge());
}
}
}
}
class Student{
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public Student() {
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.getName().hashCode()+this.getAge().hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student) {
Student s=(Student)obj;
return this.getName().equals(s.getName()) && this.getAge().equals(s.getAge());
}
return false;
}
}
运行结果如下
去重完成了!
这是为什么呢?原因是HashSet去重时自动调用hashCode()方法,这个方法会返回一个哈希值,只有当这个哈希值相等时才会调用equals()方法进行去重.
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/134086.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...