《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十七章练习题答案_第1页
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十七章练习题答案_第2页
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十七章练习题答案_第3页
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十七章练习题答案_第4页
《Java语言程序设计(基础篇)》(第10版 梁勇 著)第二十七章练习题答案_第5页
已阅读5页,还剩68页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

《Java(基础篇(10)第二十七章练习题答案27.1publicclassExercise27_01{/**Mainmethod*/publicstaticvoidmain(String[]args){MyHashMap<Integer,Integer>map=newMyHashMap<>();map.put(2,2);System.out.println("Iskey2inthemap?"+map.containsKey(2));map.remove(2);System.out.println("Iskey2inthemap?"+map.containsKey(2));}staticclassMyHashMap<K,V>implementsMyMap<K,V>{//Definethedefaulthashtablesize.privatestaticintDEFAULT_INITIAL_CAPACITY=4;//Definethemaximumhashtablesize.1<<30issameas2^30privatestaticintMAXIMUM_CAPACITY=1<<30;//Currenthashtablecapacity.privateintcapacity;//DefinedefaultloadfactorprivatestaticfloatDEFAULT_MAX_LOAD_FACTOR=0.5f;//SpecifyaloadfactorusedinthehashtableprivatefloatloadFactorThreshold;//Thenumberofentriesinthemapprivateintsize=0;//HashtableisanarraywitheachcellthatisalinkedlistMyMap.Entry<K,V>[]table;/**Constructamapwiththedefaultcapacityandloadfactor*/publicMyHashMap(){this(DEFAULT_INITIAL_CAPACITY,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacityand*defaultloadfactor*/publicMyHashMap(intinitialCapacity){this(initialCapacity,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacity*andloadfactor*/publicMyHashMap(intinitialCapacity,floatloadFactorThreshold){this.capacity=initialCapacity;this.loadFactorThreshold=loadFactorThreshold;table=newMyMap.Entry[capacity];}/**Removealloftheentriesfromthismap*/publicvoidclear(){size=0;removeEntries();}/**Returntrueifthespecifiedkeyisinthemap*/publicbooleancontainsKey(Kkey){if(get(key)!=null)returntrue;elsereturnfalse;}/**Returntrueifthismapcontainsthespecifiedvalue*/publicbooleancontainsValue(Vvalue){for(inti=0;i<table.length;i++)if(table[i]!=null&&table[i].value.equals(value))returntrue;returnfalse;}/**Returnasetofentriesinthemap*/publicjava.util.Set<MyMap.Entry<K,V>>entrySet(){java.util.Set<MyMap.Entry<K,V>>set=newjava.util.HashSet<MyMap.Entry<K,V>>();for(inti=0;i<capacity;i++)if(table[i]!=null)set.add(table[i]);returnset;}/**Returnthefirstvaluethatmatchesthespecifiedkey*/publicVget(Kkey){//Performlinearprobinginti=hash(key.hashCode());while(table[i]!=null){if(table[i].key!=null&&table[i].key.equals(key))returntable[i].value;i=(i+1)%table.length;}returnnull;}/**Returnallvaluesforthespecifiedkeyinthismap*/publicjava.util.Set<V>getAll(Kkey){java.util.Set<V>set=newjava.util.HashSet<V>();for(inti=0;i<capacity;i++)if(table[i]!=null&&table[i].key.equals(key))set.add(table[i].value);returnset;}/**Returntrueifthismapcontainsnoentries*/publicbooleanisEmpty(){returnsize==0;}/**Returnasetconsistingofthekeysinthismap*/publicjava.util.Set<K>keySet(){java.util.Set<K>set=newjava.util.HashSet<K>();for(inti=0;i<capacity;i++)if(table[i]!=null)set.add(table[i].key);returnset;}/**Addanentry(key,value)intothemap*/publicVput(Kkey,Vvalue){if(size>=capacity*loadFactorThreshold){if(capacity==MAXIMUM_CAPACITY)thrownewRuntimeException("Exceedingmaximumcapacity");rehash();}inti=hash(key.hashCode());while(table[i]!=null&&table[i].key!=null)i=(i+1)%table.length;//Addanentry(key,value)tothetabletable[i]=newMyMap.Entry<K,V>(key,value);size++;//Increasesizereturnvalue;}/**Removetheelementforthespecifiedkey*/publicvoidremove(Kkey){inti=hash(key.hashCode());while(table[i]!=null&&(table[i].key==null||!table[i].key.equals(key)))i=(i+1)%table.length;if(table[i]!=null&&table[i].key.equals(key)){//AspecialmarkerEntry(null,null)isplacedforthedeletedentrytable[i]=newMyMap.Entry<K,V>(null,null);size--;}}/**Returnthenumberofmappingsinthismap*/publicintsize(){returnsize;}/**Returnasetconsistingofthevaluesinthismap*/publicjava.util.Set<V>values(){java.util.Set<V>set=newjava.util.HashSet<V>();for(inti=0;i<capacity;i++)if(table[i]!=null)set.add(table[i].value);returnset;}/**Hashfunction*/privateinthash(inthashCode){returnhashCode%capacity;// returnsupplementalHash(hashCode)&(capacity-1);}/**Ensurethehashingisevenlydistributed*/privatestaticintsupplementalHash(inth){h^=(h>>>20)^(h>>>12);returnh^(h>>>7)^(h>>>4);}/**Removeallentriesfromeachbucket*/privatevoidremoveEntries(){for(inti=0;i<capacity;i++)table[i]=null;}/**Rehashthemap*/privatevoidrehash(){java.util.Set<Entry<K,V>>set=entrySet();//Getentriescapacity<<=1;//Doublecapacitytable=newEntry[capacity];//Createanewhashtablesize=0;//Clearsizefor(Entry<K,V>entry:set){put(entry.getKey(),entry.getValue());//Storetonewtable}}@Override/**Returnastringrepresentationforthismap*/publicStringtoString(){StringBuilderbuilder=newStringBuilder("[");for(inti=0;i<capacity;i++){if(table[i]!=null&&table[i].key!=null)builder.append(table[i].toString());}returnbuilder.append("]").toString();}}interfaceMyMap<K,V>{/**Removealloftheentriesfromthismap*/publicvoidclear();/**Returntrueifthespecifiedkeyisinthemap*/publicbooleancontainsKey(Kkey);/**Returntrueifthismapcontainsthespecifiedvalue*/publicbooleancontainsValue(Vvalue);/**Returnasetofentriesinthemap*/publicjava.util.Set<Entry<K,V>>entrySet();/**Returnthefirstvaluethatmatchesthespecifiedkey*/publicVget(Kkey);/**Returnallvaluesforthespecifiedkeyinthismap*/publicjava.util.Set<V>getAll(Kkey);/**Returntrueifthismapcontainsnoentries*/publicbooleanisEmpty();/**Returnasetconsistingofthekeysinthismap*/publicjava.util.Set<K>keySet();/**Addanentry(key,value)intothemap*/publicVput(Kkey,Vvalue);/**Removetheentriesforthespecifiedkey*/publicvoidremove(Kkey);/**Returnthenumberofmappingsinthismap*/publicintsize();/**Returnasetconsistingofthevaluesinthismap*/publicjava.util.Set<V>values();/**DefineinnerclassforEntry*/publicstaticclassEntry<K,V>{Kkey;Vvalue;publicEntry(Kkey,Vvalue){this.key=key;this.value=value;}publicKgetKey(){returnkey;}publicVgetValue(){returnvalue;}@OverridepublicStringtoString(){return"["+key+","+value+"]";}}}}27.2publicclassExercise27_02{/**Mainmethod*/publicstaticvoidmain(String[]args){MyHashMap<Integer,Integer>map=newMyHashMap<>();map.put(2,2);key2inthemap?"+map.containsKey(2));map.remove(2);System.out.println("Iskey2inthemap?"+map.containsKey(2));}staticclassMyHashMap<K,V>implementsMyMap<K,V>{//Definethedefaulthashtablesize.privatestaticintDEFAULT_INITIAL_CAPACITY=4;//Definethemaximumhashtablesize.1<<30issameas2^30privatestaticintMAXIMUM_CAPACITY=1<<30;//Currenthashtablecapacity.privateintcapacity;//DefinedefaultloadfactorprivatestaticfloatDEFAULT_MAX_LOAD_FACTOR=0.4f;//SpecifyaloadfactorusedinthehashtableprivatefloatloadFactorThreshold;//Thenumberofentriesinthemapprivateintsize=0;//HashtableisanarraywitheachcellthatisalinkedlistMyMap.Entry<K,V>[]table;/**Constructamapwiththedefaultcapacityandloadfactor*/publicMyHashMap(){this(DEFAULT_INITIAL_CAPACITY,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacityand*defaultloadfactor*/publicMyHashMap(intinitialCapacity){this(initialCapacity,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacity*andloadfactor*/publicMyHashMap(intinitialCapacity,floatloadFactorThreshold){this.capacity=initialCapacity;this.loadFactorThreshold=loadFactorThreshold;table=newMyMap.Entry[capacity];}/**Removealloftheentriesfromthismap*/publicvoidclear(){size=0;removeEntries();}/**Returntrueifthespecifiedkeyisinthemap*/publicbooleancontainsKey(Kkey){if(get(key)!=null)returntrue;elsereturnfalse;}/**Returntrueifthismapcontainsthespecifiedvalue*/publicbooleancontainsValue(Vvalue){for(inti=0;i<table.length;i++)if(table[i]!=null&&table[i].value.equals(value))returntrue;returnfalse;}/**Returnasetofentriesinthemap*/publicjava.util.Set<MyMap.Entry<K,V>>entrySet(){java.util.Set<MyMap.Entry<K,V>>set=newjava.util.HashSet<MyMap.Entry<K,V>>();for(inti=0;i<capacity;i++)if(table[i]!=null)set.add(table[i]);returnset;}/**Returnthefirstvaluethatmatchesthespecifiedkey*/publicVget(Kkey){//Performlinearprobingintk=hash(key.hashCode());inti=k;intj=1;while(table[i]!=null){if(table[i].key!=null&&table[i].key.equals(key))returntable[i].value;i=Math.abs((k+j*j)%table.length);j++;}returnnull;}/**Returnallvaluesforthespecifiedkeyinthismap*/publicjava.util.Set<V>getAll(Kkey){java.util.Set<V>set=newjava.util.HashSet<V>();for(inti=0;i<capacity;i++)if(table[i]!=null&&table[i].key.equals(key))set.add(table[i].value);returnset;}/**Returntrueifthismapcontainsnoentries*/publicbooleanisEmpty(){returnsize==0;}/**Returnasetconsistingofthekeysinthismap*/publicjava.util.Set<K>keySet(){java.util.Set<K>set=newjava.util.HashSet<K>();for(inti=0;i<capacity;i++)if(table[i]!=null)set.add(table[i].key);returnset;}/**Addanentry(key,value)intothemap*/publicVput(Kkey,Vvalue){if(size>=capacity*loadFactorThreshold){if(capacity==MAXIMUM_CAPACITY)thrownewRuntimeException("Exceedingmaximumcapacity");rehash();}intk=hash(key.hashCode());intj=1;inti=k;while(table[i]!=null&&table[i].key!=null){i=Math.abs((k+j*j)%table.length);j++;}//Addanentry(key,value)tothetabletable[i]=newMyMap.Entry<K,V>(key,value);size++;//Increasesizereturnvalue;}/**Removetheelementforthespecifiedkey*/publicvoidremove(Kkey){intk=hash(key.hashCode());intj=1;inti=k;while(table[i]!=null&&(table[i].key==null||!table[i].key.equals(key))){i=Math.abs((k+j*j)%table.length);j++;}if(table[i]!=null&&table[i].key.equals(key)){//AspecialmarkerEntry(null,null)isplacedforthedeletedentrytable[i]=newMyMap.Entry<K,V>(null,null);size--;}}/**Returnthenumberofmappingsinthismap*/publicintsize(){returnsize;}/**Returnasetconsistingofthevaluesinthismap*/publicjava.util.Set<V>values(){java.util.Set<V>set=newjava.util.HashSet<V>();for(inti=0;i<capacity;i++)if(table[i]!=null)set.add(table[i].value);returnset;}/**Hashfunction*/privateinthash(inthashCode){returnhashCode%capacity;// returnsupplementalHash(hashCode)&(capacity-1);}/**Ensurethehashingisevenlydistributed*/privatestaticintsupplementalHash(inth){h^=(h>>>20)^(h>>>12);returnh^(h>>>7)^(h>>>4);}/**Removeallentriesfromeachbucket*/privatevoidremoveEntries(){for(inti=0;i<capacity;i++)table[i]=null;}/**Rehashthemap*/privatevoidrehash(){java.util.Set<Entry<K,V>>set=entrySet();//Getentriescapacity<<=1;//Doublecapacitytable=newEntry[capacity];//Createanewhashtablesize=0;//Clearsizefor(Entry<K,V>entry:set){put(entry.getKey(),entry.getValue());//Storetonewtable}}@Override/**Returnastringrepresentationforthismap*/publicStringtoString(){StringBuilderbuilder=newStringBuilder("[");for(inti=0;i<capacity;i++){if(table[i]!=null&&table[i].key!=null)builder.append(table[i].toString());}returnbuilder.append("]").toString();}}interfaceMyMap<K,V>{/**Removealloftheentriesfromthismap*/publicvoidclear();/**Returntrueifthespecifiedkeyisinthemap*/publicbooleancontainsKey(Kkey);/**Returntrueifthismapcontainsthespecifiedvalue*/publicbooleancontainsValue(Vvalue);/**Returnasetofentriesinthemap*/publicjava.util.Set<Entry<K,V>>entrySet();/**Returnthefirstvaluethatmatchesthespecifiedkey*/publicVget(Kkey);/**Returnallvaluesforthespecifiedkeyinthismap*/publicjava.util.Set<V>getAll(Kkey);/**Returntrueifthismapcontainsnoentries*/publicbooleanisEmpty();/**Returnasetconsistingofthekeysinthismap*/publicjava.util.Set<K>keySet();/**Addanentry(key,value)intothemap*/publicVput(Kkey,Vvalue);/**Removetheentriesforthespecifiedkey*/publicvoidremove(Kkey);/**Returnthenumberofmappingsinthismap*/publicintsize();/**Returnasetconsistingofthevaluesinthismap*/publicjava.util.Set<V>values();/**DefineinnerclassforEntry*/publicstaticclassEntry<K,V>{Kkey;Vvalue;publicEntry(Kkey,Vvalue){this.key=key;this.value=value;}publicKgetKey(){returnkey;}publicVgetValue(){returnvalue;}@OverridepublicStringtoString(){return"["+key+","+value+"]";}}}}27.4importjava.util.LinkedList;publicclassExercise27_04{publicstaticvoidmain(String[]args){//CreateamapMyMap<String,Integer>map=newMyHashMap<>();30);map.put("Anderson",31);map.put("Lewis",29);map.put("Cook",29);map.put("Smith",430);System.out.println("Entriesinmap:"+map);System.out.println("Theagefor"+"Lewisis"+map.get("Lewis").intValue());System.out.println("IsSmithinthemap?"+map.containsKey("Smith"));System.out.println("Isage33inthemap?"+map.containsValue(33));map.remove("Smith");System.out.println("Entriesinmap:"+map);map.clear();System.out.println("Entriesinmap:"+map);}staticinterfaceMyMap<K,V>{/**Removealloftheentriesfromthismap*/publicvoidclear();/**Returntrueifthespecifiedkeyisinthemap*/publicbooleancontainsKey(Kkey);/**Returntrueifthismapcontainsthespecifiedvalue*/publicbooleancontainsValue(Vvalue);/**Returnasetofentriesinthemap*/publicjava.util.Set<Entry<K,V>>entrySet();/**Returnthefirstvaluethatmatchesthespecifiedkey*/publicVget(Kkey);/**Returnallvaluesforthespecifiedkeyinthismap*/publicjava.util.Set<V>getAll(Kkey);/**Returntrueifthismapcontainsnoentries*/publicbooleanisEmpty();/**Returnasetconsistingofthekeysinthismap*/publicjava.util.Set<K>keySet();/**Addanentry(key,value)intothemap*/publicVput(Kkey,Vvalue);/**Removetheentriesforthespecifiedkey*/publicvoidremove(Kkey);/**Returnthenumberofmappingsinthismap*/publicintsize();/**Returnasetconsistingofthevaluesinthismap*/publicjava.util.Set<V>values();/**DefineinnerclassforEntry*/publicstaticclassEntry<K,V>{Kkey;Vvalue;publicEntry(Kkey,Vvalue){this.key=key;this.value=value;}publicKgetKey(){returnkey;}publicVgetValue(){returnvalue;}@OverridepublicStringtoString(){return"["+key+","+value+"]";}}}staticclassMyHashMap<K,V>implementsMyMap<K,V>{//Definethedefaulthashtablesize.Mustbeapowerof2privatestaticintDEFAULT_INITIAL_CAPACITY=4;//Definethemaximumhashtablesize.1<<30issameas2^30privatestaticintMAXIMUM_CAPACITY=1<<30;//Currenthashtablecapacity.Capacityisapowerof2privateintcapacity;//DefinedefaultloadfactorprivatestaticfloatDEFAULT_MAX_LOAD_FACTOR=0.75f;//SpecifyaloadfactorusedinthehashtableprivatefloatloadFactorThreshold;//Thenumberofentriesinthemapprivateintsize=0;//HashtableisanarraywitheachcellthatisalinkedlistLinkedList<MyMap.Entry<K,V>>[]table;/**Constructamapwiththedefaultcapacityandloadfactor*/publicMyHashMap(){this(DEFAULT_INITIAL_CAPACITY,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacityanddefaultloadfactor*/publicMyHashMap(intinitialCapacity){this(initialCapacity,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacityandloadfactor*/publicMyHashMap(intinitialCapacity,floatloadFactorThreshold){if(initialCapacity>MAXIMUM_CAPACITY)this.capacity=MAXIMUM_CAPACITY;elsethis.capacity=trimToPowerOf2(initialCapacity);this.loadFactorThreshold=loadFactorThreshold;table=newLinkedList[capacity];}@Override/**Removealloftheentriesfromthismap*/publicvoidclear(){size=0;removeEntries();}@Override/**Returntrueifthespecifiedkeyisinthemap*/publicbooleancontainsKey(Kkey){if(get(key)!=null)returntrue;elsereturnfalse;}@Override/**Returntrueifthismapcontainsthevalue*/publicbooleancontainsValue(Vvalue){for(inti=0;i<capacity;i++){if(table[i]!=null){LinkedList<Entry<K,V>>bucket=table[i];for(Entry<K,V>entry:bucket)if(entry.getValue().equals(value))returntrue;}}returnfalse;}@Override/**Returnasetofentriesinthemap*/publicjava.util.Set<MyMap.Entry<K,V>>entrySet(){java.util.Set<MyMap.Entry<K,V>>set=newjava.util.HashSet<MyMap.Entry<K,V>>();for(inti=0;i<capacity;i++){if(table[i]!=null){LinkedList<Entry<K,V>>bucket=table[i];for(Entry<K,V>entry:bucket)set.add(entry);}}returnset;}@Override/**Returnthevaluethatmatchesthespecifiedkey*/publicVget(Kkey){intbucketIndex=hash(key.hashCode());if(table[bucketIndex]!=null){LinkedList<Entry<K,V>>bucket=table[bucketIndex];for(Entry<K,V>entry:bucket)if(entry.getKey().equals(key))returnentry.getValue();}returnnull;}@Override/**Returnallvaluesforthespecifiedkeyinthismap*/publicjava.util.Set<V>getAll(Kkey){java.util.Set<V>set=newjava.util.HashSet<V>();intbucketIndex=hash(key.hashCode());if(table[bucketIndex]!=null){LinkedList<Entry<K,V>>bucket=table[bucketIndex];for(Entry<K,V>entry:bucket)if(entry.getKey().equals(key))set.add(entry.getValue());}returnset;}@Override/**Returntrueifthismapcontainsnoentries*/publicbooleanisEmpty(){returnsize==0;}@Override/**Returnasetconsistingofthekeysinthismap*/publicjava.util.Set<K>keySet(){java.util.Set<K>set=newjava.util.HashSet<K>();for(inti=0;i<capacity;i++){if(table[i]!=null){LinkedList<Entry<K,V>>bucket=table[i];for(Entry<K,V>entry:bucket)set.add(entry.getKey());}}returnset;}@Override/**Addanentry(key,value)intothemap*/publicVput(Kkey,Vvalue){if(size>=capacity*loadFactorThreshold){if(capacity==MAXIMUM_CAPACITY)thrownewRuntimeException("Exceedingmaximumcapacity");rehash();}intbucketIndex=hash(key.hashCode());//Createalinkedlistforthebucketifitisnotcreatedif(table[bucketIndex]==null){table[bucketIndex]=newLinkedList<Entry<K,V>>();}//Addanentry(key,value)tohashTable[index]MyMap.Entry<K,V>(key,value));size++;//Increasesizereturnvalue;}@Override/**Removetheentriesforthespecifiedkey*/publicvoidremove(Kkey){intbucketIndex=hash(key.hashCode());//Removethefirstentrythatmatchesthekeyfromabucketif(table[bucketIndex]!=null){LinkedList<Entry<K,V>>bucket=table[bucketIndex];for(Entry<K,V>entry:bucket)if(entry.getKey().equals(key)){bucket.remove(entry);size--;//Decreasesizebreak;//Removejustoneentrythatmatchesthekey}}}@Override/**Returnthenumberofmappingsinthismap*/publicintsize(){returnsize;}@Override/**Returnasetconsistingofthevaluesinthismap*/publicjava.util.Set<V>values(){java.util.Set<V>set=newjava.util.HashSet<V>();for(inti=0;i<capacity;i++){if(table[i]!=null){LinkedList<Entry<K,V>>bucket=table[i];for(Entry<K,V>entry:bucket)set.add(entry.getValue());}}returnset;}/**Hashfunction*/privateinthash(inthashCode){returnsupplementalHash(hashCode)&(capacity-1);}/**Ensurethehashingisevenlydistributed*/privatestaticintsupplementalHash(inth){h^=(h>>>20)^(h>>>12);returnh^(h>>>7)^(h>>>4);}/**Returnapowerof2forinitialCapacity*/privateinttrimToPowerOf2(intinitialCapacity){intcapacity=1;while(capacity<initialCapacity){capacity<<=1;}returncapacity;}/**Removeallentriesfromeachbucket*/privatevoidremoveEntries(){for(inti=0;i<capacity;i++){if(table[i]!=null){table[i].clear();}}}/**Rehashthemap*/privatevoidrehash(){java.util.Set<Entry<K,V>>set=entrySet();//Getentriescapacity<<=1;//Doublecapacitytable=newLinkedList[capacity];//Createanewhashtablesize=0;//Clearsizefor(Entry<K,V>entry:set){put(entry.getKey(),entry.getValue());//Storetonewtable}}@OverridepublicStringtoString(){StringBuilderbuilder=newStringBuilder("[");for(inti=0;i<capacity;i++){if(table[i]!=null&&table[i].size()>0)for(Entry<K,V>entry:table[i])builder.append(entry);}builder.append("]");returnbuilder.toString();}}}27.6importjavafx.application.Application;importjavafx.stage.Stage;importjavafx.scene.Scene;importjavafx.scene.control.Button;importjavafx.scene.control.Label;importjavafx.scene.control.TextField;importjavafx.scene.layout.BorderPane;importjavafx.scene.layout.HBox;importjavafx.scene.layout.Pane;importjavafx.scene.paint.Color;importjavafx.scene.shape.Rectangle;importjavafx.scene.text.Text;importjavafx.geometry.Pos;importjavafx.scene.control.ScrollPane;importjavafx.scene.layout.VBox;publicclassExercise27_06extendsApplication{privateMyHashMap<Integer,Integer>map=newMyHashMap<>(11);privateHashViewview=newHashView();privateButtonbtInsert=newButton("Insert");privateButtonbtDelete=newButton("Delete");privateButtonbtSearch=newButton("Search");privateButtonbtRemoveAll=newButton("RemoveAll");privateTextFieldtfNumber=newTextField();privateTextFieldtfInitialTableSize=newTextField();privateTextFieldtfLoadFactorThreshold=newTextField();@Override//OverridethestartmethodintheApplicationclasspublicvoidstart(StageprimaryStage){BorderPanepane=newBorderPane();HBoxhBox1=newHBox(5);hBox1.getChildren().addAll(newLabel("Enterinitialtablesize:"),tfInitialTableSize,newLabel("Enteraloadfactorthreshold:tfLoadFactorThreshold);hBox1.setAlignment(Pos.CENTER);HBoxhBox2=newHBox(5);hBox2.getChildren().addAll(newLabel("Enteravalue:"),tfNumber,btInsert,btDelete,btSearch);hBox2.setAlignment(Pos.CENTER);red;-fx-padding:2");HBoxhBox3=newHBox(5);hBox3.getChildren().addAll(hBox2,btRemoveAll);hBox3.setAlignment(Pos.CENTER);VBoxvBox=newVBox(5);vBox.getChildren().addAll(hBox1,hBox3);LabellblStatus=newLabel();pane.setTop(lblStatus);BorderPane.setAlignment(lblStatus,Pos.CENTER);pane.setCenter(newScrollPane(view));pane.setBottom(vBox);tfNumber.setPrefColumnCount(2);tfInitialTableSize.setPrefColumnCount(2);tfLoadFactorThreshold.setPrefColumnCount(2);view.repaint();//CreateasceneandplacethepaneinthestageScenescene=newScene(pane,650,250);primaryStage.setTitle("Exercise27_06:LinearProbingHashingAnimation");//SetthestagetitleprimaryStage.setScene(scene);//PlacethesceneinthestageprimaryStage.show();//DisplaythestagebtInsert.setOnAction(e->{try{intkey=Integer.parseInt(tfNumber.getText());if(map.containsKey(key)){lblStatus.setText(key+"isalreadyinthetable");}else{map.put(Integer.parseInt(tfNumber.getText()),1);lblStatus.setText(key+"isinsertedinthetable");}view.repaint();}catch(NumberFormatExceptionex){numberinthetextfield");}});btDelete.setOnAction(e->{map.remove(Integer.parseInt(tfNumber.getText()));lblStatus.setText(tfNumber.getText()isdeletedfromthetable");view.repaint();});btRemoveAll.setOnAction(e->{map.clear();entriedareremovedfromthetable");view.repaint();});tfInitialTableSize.setOnAction(e->{try{map=newMyHashMap<Integer,Integer>(Integer.parseInt(tfInitialTableSize.getText()));view.repaint();lblStatus.setText("Tablesizeischanged");}catch(NumberFormatExceptionex){numberinthetextfield");}});btSearch.setOnAction(e->{try{intkey=Integer.parseInt(tfNumber.getText());if(map.containsKey(key)){lblStatus.setText(key+"isinthetable");}else{lblStatus.setText(key+"isnotinthetable");}}catch(NumberFormatExceptionex){numberinthetextfield");}});tfLoadFactorThreshold.setOnAction(e->{try{doubleloadFactorThreshold=Double.parseDouble(tfLoadFactorThreshold.getText());loadFactorThreshold);view.repaint();thresholdischanged");}catch(NumberFormatExceptionex){lblStatus.setText("Ihetextfield");}});}/**ThemainmethodisonlyneededfortheIDEwithlimitedJavaFXsupport.Notneededforrunningfromthecommandline.*/publicstaticvoidmain(String[]args){launch(args);}privateclassHashViewextendsPane{privateintstartingX=20;privateintstartingY=20;privateintboxWidth=40;privateintboxHeight=20;protectedvoidrepaint(){getChildren().clear();getChildren().add(newText(startingX,startingY,"Tablesize="+map.capacity+".Numberofkeys="+map.size));getChildren().add(newText(startingX,startingY+20,"Loadfactor="+1.0*map.size/map.capacityLoadfactorthreshold="+map.loadFactorThreshold+"."));intx=startingX;inty=startingY+55;for(inti=0;i<map.capacity;i++){Text(x,y,"["+i+"]"));Rectanglerectangle=newRectangle(startingX+35,y-15,boxWidth,boxHeight);rectangle.setFill(Color.WHITE);rectangle.setStroke(Color.BLACK);getChildren().add(rectangle);y+=20;}x+=50;y=startingY+55;for(inti=0;i<map.capacity;i++){if(map.table[i]!=null&&map.table[i].key!=null){w,,y+}elseif(map.table[i]!=null&&map.table[i].key==null){w,,"}y+=20;}}}staticclassMyHashMap<K,V>implementsMyMap<K,V>{//Definethedefaulthashtablesize.privatestaticintDEFAULT_INITIAL_CAPACITY=4;//Definethemaximumhashtablesize.1<<30issameas2^30privatestaticintMAXIMUM_CAPACITY=1<<30;//Currenthashtablecapacity.privateintcapacity;//DefinedefaultloadfactorprivatestaticfloatDEFAULT_MAX_LOAD_FACTOR=0.5f;//SpecifyaloadfactorusedinthehashtableprivatefloatloadFactorThreshold;publicvoidsetLoadFactorThreshold(floatloadFactorThreshold){this.loadFactorThreshold=loadFactorThreshold;}//Thenumberofentriesinthemapprivateintsize=0;//HashtableisanarraywitheachcellthatisalinkedlistMyMap.Entry<K,V>[]table;/**Constructamapwiththedefaultcapacityandloadfactor*/publicMyHashMap(){this(DEFAULT_INITIAL_CAPACITY,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacityanddefaultloadfactor*/publicMyHashMap(intinitialCapacity){this(initialCapacity,DEFAULT_MAX_LOAD_FACTOR);}/**Constructamapwiththespecifiedinitialcapacityandloadfactor*/publicMyHashMap(intinitialCapacity,floatloadFactorThreshold){this.capacity=initialCapacity;this.loadFactorThreshold=loadFactorThreshold;table=newMyMap.Entry[capacity];}/**Removealloftheentriesfromthism

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论