首页 > 代码库 > 练习 HashSet 去重复

练习 HashSet 去重复

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 22.0px Monaco } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; font: 22.0px Monaco; min-height: 30.0px } p.p3 { margin: 0.0px 0.0px 0.0px 0.0px; font: 22.0px Monaco; color: #931a68 } p.p4 { margin: 0.0px 0.0px 0.0px 0.0px; font: 22.0px Monaco; color: #4e9072 } p.p5 { margin: 0.0px 0.0px 0.0px 0.0px; font: 22.0px Monaco; color: #3933ff } p.p6 { margin: 0.0px 0.0px 0.0px 0.0px; font: 22.0px Monaco; color: #777777 } span.s1 { color: #931a68 } span.s2 { text-decoration: underline } span.s3 { color: #000000 } span.s4 { color: #0326cc } span.s5 { color: #7e504f } span.s6 { color: #91afcb } span.Apple-tab-span { white-space: pre }</style>

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 去重复