您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 项目/工程管理 > HashSet初步认识
HashTree:底层数据结构是:哈希表,线程不安全(其底层HashMap实例的默认初始容量是16,加载因子是0.75,如果对于迭代性能要求比较高,对加载因子设置降低或者默认),通过hashCode方法和equals方法来保证元素的唯一性。Java代码1./**2.*Constructsanew,emptyset;thebackingttHashMap/ttinstancehas3.*defaultinitialcapacity(16)andloadfactor(0.75).4.*/5.publicHashSet(){6.=newHashMapE,Object();7.}比较原理:先判断类中的属性各个hashcode计算的值,如hashcode值相同才会去判断equals,否则,是不会调用equals方法的。根据以上原理得知,我们必须要重写hashcode()和equals()方法,Java代码1.importjava.util.HashSet;2.importjava.util.Iterator;3.importjava.util.Set;4.5.publicclassStudent{6.7.privatestaticfinallongserialVersionUID=1L;8.privateStringid;9.privateStringname;10.privateintage;11.12.publicStudent(Stringid,Stringname,intage){13.super();14.this.id=id;15.this.name=name;16.this.age=age;17.}18.19.publicStudent(){20.super();21.//TODOAuto-generatedconstructorstub22.}23.24.publicStringgetId(){25.returnid;26.}27.28.publicvoidsetId(Stringid){29.this.id=id;30.}31.32.publicStringgetName(){33.returnname;34.}35.36.publicvoidsetName(Stringname){37.this.name=name;38.}39.40.publicintgetAge(){41.returnage;42.}43.44.publicvoidsetAge(intage){45.this.age=age;46.}47.48.@Override49.publicStringtoString(){50.returnStudent[id=+id+,name=+name+,age=+age+];51.}52.53.@Override54.publicinthashCode(){55.finalintprime=31;//为什么是31,可以思考一下,到时再整理出来56.intresult=1;57.result=prime*result+age;58.result=prime*result+((id==null)?0:id.hashCode());59.result=prime*result+((name==null)?0:name.hashCode());60.System.out.println(hashCodemethod:+result);61.returnresult;62.}63.64.@Override65.publicbooleanequals(Objectobj){66.if(this==obj)67.returntrue;68.if(obj==null)69.returnfalse;70.if(getClass()!=obj.getClass())71.returnfalse;72.Studentother=(Student)obj;73.if(age!=other.age){74.75.returntrue;76.}77.if(id==null){78.if(other.id!=null)79.returnfalse;80.}elseif(!id.equals(other.id))81.returnfalse;82.if(name==null){83.if(other.name!=null)84.returnfalse;85.}elseif(!name.equals(other.name))86.returnfalse;87.returntrue;88.}89.90.publicstaticvoidmain(String[]args){91.SetStudentset=newHashSetStudent();92.Studentstudent1=newStudent(1,Tom,16);93.Studentstudent2=newStudent(2,Lucy,13);94.Studentstudent2_1=newStudent(2,Lucy,13);95.Studentstudent3=newStudent(3,Peter,14);96.97.set.add(student1);98.set.add(student2);99.set.add(student2_1);100.set.add(student3);101.IteratorStudentiterator=set.iterator();102.while(iterator.hasNext()){103.Studentnext=iterator.next();104.System.out.println(next.getName()+:+next.getAge());105.106.}107.108.}109.}同样contains(obj)方法中,也对比顺序是hashCode和equals(o)代码如下Java代码1./**2.*Returnstheentryassociatedwiththespecifiedkeyinthe3.*HashMap.ReturnsnulliftheHashMapcontainsnomapping4.*forthekey.5.*/6.finalEntryK,VgetEntry(Objectkey){7.inthash=(key==null)?0:hash(key.hashCode());8.for(EntryK,Ve=table[indexFor(hash,table.length)];9.e!=null;10.e=e.next){11.Objectk;12.if(e.hash==hash&&13.((k=e.key)==key||(key!=null&&key.equals(k))))14.returne;15.}16.returnnull;17.}
本文标题:HashSet初步认识
链接地址:https://www.777doc.com/doc-2875806 .html