Set代表了集合
集合中要求元素是不能重复复的。
什么叫重复?
Set中是没有重复标准的。
HashSet如何判段重复?
hashset无法帮助自定义类型判断什么是逻辑上的重复。
hashset判重步骤:
代码:
package d;
import java.util.*;
class Person
{
private String name;
private int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public boolean equals(Object x)
{
if(x instanceof Person == false) return false;
Person p = (Person)x;
return this.name.equals(p.name) && this.age==p.age;
//return true;
}
public int hashCode()
{
return this.name.hashCode() + this.age;
//return 100;
}
public String toString(){ return name + ": " + age; }
}
public class HashSetTest {
public static void main(String[] args)
{
Set<Person> a = new HashSet<Person>();
a.add(new Person("zhang",10));
a.add(new Person("zhang",11));
a.add(new Person("zhang",10));
a.add(new Person("li",10));
System.out.println(a);
/*
Set<String> a = new HashSet<String>();
a.add("abc");
a.add("xyz");
a.add("abc");
System.out.println(a);
*/
}
}