Case Introduction: The development of a container to store key-value pairs, keys to store English names, values for the Chinese name, the key value of the use of internal classes to encapsulate;
Case Design:
① uses static inner classes to encapsulate key-value pairs of data;
② container Default size is 5, more than the expansion of its twice times;
③ returns the data in the container by calling the Entryarrays method;
1 Importjava.util.Arrays;2 Public classentrydemo{3 Public Static voidMain (String []args) {4MyContainer container=NewMyContainer ();5Container.put ("Jack", "Jake");6Container.put ("Jay", "Jay Chou"));7Container.put ("John", "John");8Container.put ("Rose", "Ross");9Container.put ("Jack", "Zhang San");Ten OneMycontainer.entry[] Entrys=container.entryarrays (); A for(inti=0;i<entrys.length;i++){ -Mycontainer.entry entry=Entrys[i]; -System.out.println (Entry.getkey () + "--" +Entry.getvalue ()); the } - } - } - + classmycontainer{ - //an array of entry objects, with a default size of 5 + PrivateEntry[] Entrys=NewEntry[5]; A Private intCount=0; at - //externally provides an interface for storing encapsulated data in a container - Public voidput (String key,string value) { -Entry entry=NewEntry (); - Entry.setkey (key); - Entry.setvalue (value); inEntrys[count++]=entry;//storing entry objects into arrays - //Expansion of Arrays to if(count>=entrys.length) { + //size of new array after expansion - intNewcapacity=entrys.length*2; the //Copy the data from the old array into a new array of length newcapacity *entrys=arrays.copyof (entrys,newcapacity); $ }Panax Notoginseng } - the //returns the contents of the container with data + Publicentry[] Entryarrays () { A returnArrays.copyofrange (entrys,0, count); the } + - //encapsulates a key-value pair in a entry object $ Public Static classentry{ $ PrivateString key; - PrivateString value; - Public voidSetkey (String key) { the This. key=key; - }Wuyi PublicString GetKey () { the returnkey; - } Wu Public voidSetValue (String value) { - This. value=value; About } $ PublicString GetValue () { - returnvalue; - } - } A}
Develop a container for storing data using an internal class