练习 HashSet 去重复
Posted 奥雷迪尔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了练习 HashSet 去重复相关的知识,希望对你有一定的参考价值。
package com.rf.xs.list;
import java.util.HashSet;
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public boolean equals(Object obj){
if(obj instanceof Person){ //判断obj是不是 Person类型 instanceof:运算符
Person p = (Person)obj;
return this.name.equals(p.name)&& this.age == p.age;
}
return false;
}
public int HashCode(){
return 0;
}
public String toString(){
return"Person[name="+name+",age="+age+"]";
}
@Override
public int hashCode() { //如果哈希值相同,才回判断equlas是否相同,如果哈希值不同,不会调用equlas方法。
// TODO Auto-generated method stub
return 0;
}
}
package com.rf.xs.list;
import java.util.HashSet;
import java.util.Iterator;
public class TextHashSet01 {
public static void main(String[] args) {
Person per1 = new Person("q", 18);
Person per2 = new Person("q", 18);
Person per3 = new Person("u", 18);
Person per4 = new Person("w", 28);
Person per5 = new Person("r", 17);
//Person[] p = { per1, per2, per3, per4, per5 };
HashSet<Person> l = new HashSet<Person>();
l.add(per1);
l.add(per2);
l.add(per3);
l.add(per4);
l.add(per5);
HashSet<Person> pers = qc(l);
System.out.println(pers);
}
public static HashSet<Person> qc(HashSet<Person> l){
HashSet<Person> pers = new HashSet<Person>();
Iterator<Person> m = l.iterator();
while (m.hasNext()) {
Person n = m.next();
if (!pers.contains(n)) {
pers.add(n);
}
}
return pers;
}
}
以上是关于练习 HashSet 去重复的主要内容,如果未能解决你的问题,请参考以下文章
Python练习题4(列表去重):[5,3,4,'ok',4,3,'abc',8,52,'ok']去除列表中重复内容 方法一:使用set 方法二:不使用