版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
《Java(基礎(chǔ)篇(10)第二十七章練習(xí)題答案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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 物理必修一課件
- 2024年寧波客運(yùn)資格證仿真試題
- 2024年景德鎮(zhèn)客運(yùn)資格證情景題
- 2024年申請(qǐng)參加客運(yùn)駕駛員從業(yè)資格證考試
- 2024年昭通經(jīng)營(yíng)性道路旅客運(yùn)輸駕駛員從業(yè)資格考試題庫(kù)
- 2024年濱州客運(yùn)從業(yè)資格證報(bào)名考試題目
- 2024年柳州申請(qǐng)客運(yùn)從業(yè)資格證模擬考試
- 2024年肇慶申請(qǐng)客運(yùn)從業(yè)資格證考試
- 2025屆山東省青島西海岸新區(qū)第一中學(xué)英語(yǔ)高三上期末檢測(cè)模擬試題含解析
- 長(zhǎng)沙市重點(diǎn)中學(xué)2025屆高二上生物期末考試試題含解析
- 北師大版小學(xué)數(shù)學(xué)六年級(jí)上冊(cè)《這月我當(dāng)家》教案
- 第4章 軸與輪轂的連接和其他連接
- 塑料包裝袋出廠檢驗(yàn)報(bào)告單
- 光伏發(fā)電項(xiàng)目施工方案及技術(shù)措施
- 山東信發(fā)中興碳素罐式爐燃控系統(tǒng)技術(shù)協(xié)議
- 高速收費(fèi)基本知識(shí)
- 《記念劉和珍君》教案一等獎(jiǎng)
- 委托檢驗(yàn)受托方能力現(xiàn)場(chǎng)調(diào)查評(píng)估表
- 小學(xué)一年級(jí)數(shù)字描紅帶筆順0-9-田字格虛線
- 降糖藥的使用及注意事項(xiàng)
- 小學(xué)語(yǔ)文學(xué)科帶頭人匯報(bào)材料
評(píng)論
0/150
提交評(píng)論