hashcode重寫,hashSet操作


public class Student /*implements Comparable*/{
private long id;
private String name;
private int age;
public Student(){}
public Student(long id, String name,int age){
this.id=id;
this.name=name;
this.age=age;
}
public void setId(long id){
this.id=id;
}
public long getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age=age;
}
public int getAge(){
return age;
}
public boolean equals(Object obj){
System.out.println("stu.equals()");
if(obj==null){
return false;
}
if(this==obj){
return true;
}
if(!(this.getClass()==obj.getClass()))//getClass獲取運行時類,運行的名字
{
return false;
}
Student stu=(Student)obj;
return (this.id==stu.getId())&&this.name.equals(stu.getName())&&(this.age==stu.getAge());
}
public String toString(){
return id+","+name+","+age;
}
public int hashCode(){//重寫hashcode
// return (int)(this.id);
int hashcode=1;
hashcode=hashcode*31+(int)this.id;
hashcode=hashcode*31+this.name.hashCode();
hashcode=hashcode*31+this.age;//(n<<5)-n=n*31
return hashcode;
// return (int)(this.id+this.age);
}
/*public int compareTo(Object obj)
Student stu=(Student)obj;
Long thisId=this.id;
Long stuId=stu.getId();
if(thisId.compareTo(stuId)==0){
 if(this.name.compareTo(stu.getName())==0) {
return this.age-stu.getAge();
}
return this.name.compareTo(stu.getName());
}


return thisId.compareTo(stuId);
}*/
public static void main(String args[]){
Student stu=new Student(1,"zhangsan",20);
Student stu2=new Student(1,"zhangsan",20);
System.out.println(stu.equals(stu2));
}

}


import java.util.*;


public class HashSetTest{
public static void main(String args[]){
//HashSet set=new HashSet(5,0.4f);
HashSet set=new HashSet();//默認的初始容量16,hash擴展因子爲0.75
    set.add(1);
set.add("2");
set.add(3);
set.add(4.0f);
set.add(10.0);
set.add("2");
set.add(10.0);//只會出現一個10.0,hashcode爲數字本身
Iterator it=set.iterator();
while(it.hasNext()){
System.out.print(it.next()+"  ");
}
set.remove(10.0);
for(Object obj:set){
System.out.print(obj+"  ");
}
System.out.println("");
HashSet set2=new HashSet();
set2.add(new Student(5,"hange",40));//hashcode爲地址計算
set2.add(new Student(6,"shang",20));
set2.add(new Student(7,"zhang",30));
set2.add(new Student(5,"hange",40));
set2.add(new Student(4,"testt",40));
for(Object obj:set2){
System.out.println(obj);
}
   }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章