首页 > 代码库 > HashSet的特殊特性
HashSet的特殊特性
HashSet除了在元素的存储上是无序的以外,还是不能够存储重复的元素。
HashSet如何判断元素是否重复呢?是根据元素继承的两个方法来判断,hashCode和equals,当存储元素时,首先判断要存入的元素和已存在的元素的哈希值是否相同,若不相同存入,若相同则利用equals判断两个元素是否相同,若不相同,则存入,若相同则放弃。而hashCode和equlas是在存入元素自动调用的。
一下继续利用Person类举例
import java.util.*;
class Person
{
????private String name; //姓名
????private int age;????//年龄
?
????public Person(String name, int age)
????{
????????this.name = name;
????????this.age = age;
????}
????//用于生成自定义的哈希值
????public int hashCode()
????{
????????return this.name.hashCode()+this.age*36;
????}
????//自己定义比较规则,与ArrayList相同
????public boolean equals(Object obj)
????{
????????if(!(obj instanceof Person))
????????????return false;
????????Person p = (Person)obj;
????????return p.getName().equals(this.getName()) && (p.getAge() == this.getAge());
????}
????public String getName()
????{
????????return this.name;
????}
?
????public int getAge()
????{
????????return this.age;
????}
?
????public void setName(String name)
????{
????????this.name = name;
????}
?
????public void setAge(int age)
????{
????????this.age = age;
????}
}
?
public class Test
{
????public static void main(String[] args)
????{
????????HashSet<Person> hs = new HashSet<>();
?
????????hs.add(new Person("zhangsan", 23));
????????hs.add(new Person("lisi", 23));
????????hs.add(new Person("zhangsan", 23));
????????hs.add(new Person("wangwu", 35));
????????hs.add(new Person("zhangsan", 67));
????????hs.add(new Person("zhaoliu", 45));
?
????????Iterator<Person> it = hs.iterator();
?
????????while(it.hasNext())
????????{
????????????Person p = it.next();
????????????System.out.println(p.getName()+"...."+p.getAge());
????????}
????}
}
HashSet的特殊特性