版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
《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. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 手術(shù)準(zhǔn)備與操作規(guī)范管理制度
- 手術(shù)環(huán)境管理制度
- 2022年三年級語文下冊第四單元主題閱讀+答題技巧(含答案、解析)部編版
- 2024年客運證考什么的
- 2024年嘉峪關(guān)小型客運從業(yè)資格證考試題答案
- 2024年宜春客運從業(yè)資格證模擬考試練習(xí)題
- 2024年道路客運從業(yè)資格證繼續(xù)教育模擬考試
- 2024年綿陽a1客運資格證
- 2024年海口客運從業(yè)資格證的考試題目
- 2024年河北客運上崗考試都考什么科目
- 央國企信創(chuàng)化與數(shù)字化轉(zhuǎn)型規(guī)劃實施
- 1.四方埔社區(qū)服務(wù)中心場地管理制度
- 智慧城市治理CIM平臺建設(shè)方案
- 心肺復(fù)蘇后疾病的病理生理和預(yù)后
- 《餐飲服務(wù)的特點》課件
- 少兒科學(xué)實驗-直升飛機
- 全國優(yōu)質(zhì)課一等獎《計算機應(yīng)用基礎(chǔ)-計算機系統(tǒng)組成》多媒體課件
- 庭審結(jié)束后提交補充意見范本
- 古詩詞中的數(shù)學(xué)
- 26 西門豹治鄴 一等獎創(chuàng)新教學(xué)設(shè)計(2課時)
- 關(guān)于成立消防安全組織機構(gòu)的通知
評論
0/150
提交評論