关于集合中理解的问题

来源:互联网 发布:travian 兵工廠 計算法 编辑:程序博客网 时间:2024/05/18 00:40
package com.isannian.java;import java.util.HashSet;public class SetTest{  public static void main(String[] args){HashSet set=new HashSet();//System.out.println(set.add("a"));//set.add("b");//set.add("c");//System.out.println(set.add("a"));//System.out.println(set);////set.add(new RenLei("zhangsan"));//set.add(new RenLei("lisi"));//System.out.println(set);//RenLei ren=new RenLei("zhangsan");//set.add(ren);//set.add(ren);//System.out.println(set);////String s1 =new String("lisi");//String s2 =new String("lisi");//System.out.println("hashcode :"+(s1.hashCode()==s2.hashCode()));//set.add(s1);//set.add(s2);//System.out.println(set);RenLei r1 =new RenLei("a");RenLei r2 =new RenLei("a");System.out.println("hashcode :"+(r1.hashCode()==r2.hashCode()));System.out.println("equals: "+ r1.equals(r2));set.add(r1);set.add(r2);System.out.println(set);}} class RenLei{   String name;public RenLei(String name){ this.name =name;  }//@Override//public int hashCode()//{//final int prime = 31;//int result = 1;//result = prime * result + ((name == null) ? 0 : name.hashCode());//return result;//}////@Override//public boolean equals(Object obj)//{//if (this == obj)//return true;//if (obj == null)//return false;//if (getClass() != obj.getClass())//return false;//RenLei other = (RenLei) obj;//if (name == null)//{//if (other.name != null)//return false;//} else if (!name.equals(other.name))//return false;//return true;//}@Overridepublic int hashCode(){// TODO Auto-generated method stubreturn this.name.hashCode();} @Overridepublic boolean equals(Object obj){if(this == obj){return true;}if(null != obj && obj instanceof RenLei){RenLei r=(RenLei) obj;if(name.equals(r.name))//obj.equals(r.name){return true;}}return false;}}

set 集合中(接口)

当使用 HashSet 时,使用add方法时,对象会自动调用hashCode() 方法,判断 已经存储在集合中的对象的hash code值是否与增加对象的hash code 值一致;如果不一致,直接加进去;

如果 一致, 在进行 equals方法比较,equals方法如果返回true,表示对象已经加进去了,就不会再添加新的 对象! 

否则加进去!


如果重写 Object 中的 equals  方法  ,那么也要重写 hashCode 方法,反之亦然!






原创粉丝点击