首页 > 代码库 > 练习 HashSet 去重复
练习 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 去重复