JAVA之HashSet去重(本身无序不重复,针对对象去重)

package yu;


import java.util.HashSet;
import java.util.Iterator;


//无序不重复(但是对象要想不重复,要重写以下方法)


public class Main {
public static void main(String[] args) {

HashSet<Student> set=new HashSet<>();

Student stu1=new Student("yu1", "1");
Student stu2=new Student("yu2", "2");
Student stu3=new Student("yu3", "3");
Student stu4=new Student("yu3", "3");//重复的对象

set.add(stu1);
set.add(stu2);
set.add(stu3);
set.add(stu4);

//迭代器遍历
Iterator<Student> it=set.iterator();
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
}
}
class Student{
String name;

String id;


public Student(String name, String id) {
super();
this.name = name;
this.id = id;
}

@Override

        //Java中所有的类都是继承于Object类,自带tostring方法,输出的是类名和内存首地址,

        //通过重写toString方法,得到自己想要的打印结果

        public String toString() {

return id+":"+name;
}


//通过重写这两个方法实现对象的去重(eclipse可自动生成)
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
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 (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值