您的位置:首页 > 其它

类集HashSet

2015-11-08 21:31 162 查看

HashSet

(采用散列存储(哈希算法就是计算散列存储位置的一种算法),所有是无序的,重复的只会出现一次(因为相同东西算出来的位置是一样的))

如果是我们自己定义的类就会出现重复,除非你重写equals和hashCode方法才会删除重复。

import java.util.HashSet;

public class TreeSetDemo1 {

public static void main(String[] args) {

HashSet<Dog> ts = new HashSet<Dog>();
ts.add(new Dog("1", 33));
ts.add(new Dog("2", 2));
ts.add(new Dog("2", 44));
ts.add(new Dog("2", 12));
ts.add(new Dog("3", 13));
ts.add(new Dog("4", 14));
System.out.println(ts);
}

}

class Dog{
private String name;
private int age;

public Dog(String name, int age) {
this.name = name;
this.age = 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 String toString() {
return (this.name + ":" + this.age);
}
public boolean equals(Object obj){
//首先判断是不是我们要判断的类型
if(!(obj instanceof Dog)){
return false;
}
//判断是不是不同名字,但是指向了同一个
if(this == obj ){
return true;
}
//判断是不同的对象,但是值确是一样
Dog d = (Dog)obj;
if(this.age == d.getAge()&&this.getName()==d.getName()){
return true;
}else{
return false;
}

}

public int hashCode(){
return this.name.hashCode();
//return this.name.hashCode()*this.age;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 hashcode 存储