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);
}
   }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值