Since the last article is too lengthy to talk about in a single-column collection, this article will describe the use of a two-row set map separately.
Map dual-column Collection root interface
If you have millions of students stored in the program and often need to use the number to search for a student, the data structure that needs to be effective is map. A map is a container that stores elements according to key (key), which is like a subscript, and the subscript is an integer in the list. In the Map key (key) you can make any type of object. There can be no duplicate keys (key) in the map, and each key will have a corresponding value (key). A key (key) and its corresponding value form an element in the map collection.
The elements in map are two objects, an object as a key, and an object as a value. The key is unique and the value is repeatable (the new value overrides the old value).
Common method of Map interface
| Operation |
meaning |
return value |
| Put (K key, V value) |
When the element is stored, the addition fails when the key is in the same time, but the added value overrides the substituted value and returns the value that is replaced, or null if the element is added successfully. |
Object |
| Putall (Map m) |
Call this method to add an element of another map collection to the current collection. |
void |
| Remove (Object key) |
Deletes its value according to the key and returns the caller |
Object |
| Clear () |
Emptying the collection Object |
void |
| Get (Key) |
Get its value by key |
Object |
| Size () |
Get length |
Int |
| VALUES () |
Gets all the values of the map collection and returns a collection in the collection |
Collection |
| IsEmpty () |
A length of 0 returns true otherwise false |
Boolean |
| ContainsKey (Object key) |
Determines whether the specified key is contained in the collection |
Boolean |
| Containsvalue (Object value) |
Determines whether the specified value is contained in the collection |
Boolean |
Example of replacing value with the same key
Public class _main44 { Public Static void Main(string[] args) {Map<integer,string> Map =NewHashmap<integer,string> (); Map.put (1,"a"); Map.put (2,"B"); Map.put (3,"C"); Map.put (4,"D");//key is the same, value is different, and the value returned is the one that is replacedSystem.out.println (Map.put (1,"G")); SYSTEM.OUT.PRINTLN (map);//Extracts all of the value in the map and returns it to the collection collectioncollection<string> C = map.values (); System.out.println (c); }}
Operation Result:
Traversal of the Map collection
Note that in the collection of map systems, there is no iterator iterator available, so the map collection has its own iterative approach.
1, Set KeySet (): This method returns all the keys in the map collection and stores them in the set collection.
2, Set EntrySet (): Gets all the key-value pairs (relationships) in the map collection and returns to a set set.
To iterate over a map collection by keyset
Steps:
1. Call the keyset method of the map interface to get all the keys in the map collection and store them in the set collection.
2. Create an iterator through the iterator method of the set interface, traversing the key values stored in the Set collection.
3. Get the value of the corresponding key through the Get method of the map collection during traversal.
Class Demo1 { Public Static void Main(string[] args) {map<string, string> Map =NewHashmap<string, string> (); Map.put ("Zhang San","Little Red"); Map.put ("John Doe","Xiao Lan"); Map.put ("Harry","Little Flower");//Get the key and value of the map collection by keyset methodset<string> keys = Map.keyset ();//Use the iterator method of the set collection to create an iterator objectIterator<string> it = Keys.iterator (); while(It.hasnext ()) {//Get the key of the lock store in the set collection by IterationString key = It.next ();//Get the value of the corresponding key by the Get method of the map collectionSystem.out.println ("key:"+ key +"Value:"+ map.get (key)); } }}
Operation Result:
To iterate over a map collection by EntrySet
Steps:
1. Call the EntrySet method of the map collection to get all the key-value pairs and return to the Set collection
2. Create an iterator for the set collection, traversing all the key-value pairs (relationship) objects in the Set collection
3. When traversing a key-value pair, the unique method of invoking the entry interface via the key value pair Object Getkey () and GetValue () gets the keys and values that each map combines.
Public class Demo1 { Public Static void Main(string[] args) {map<string, string> Map =NewHashmap<string, string> (); Map.put ("Zhang San","Little Red"); Map.put ("John Doe","Xiao Lan"); Map.put ("Harry","Little Flower");//Call the EntrySet method to get the key-value pair and store it in the Set collectionset<map.entry<string, string>> entries = Map.entryset ();//Create an iterator from a set setiterator<map.entry<string, string>> Iterator = Entries.iterator (); while(Iterator.hasnext ()) {//Iterate out all key-value pairs (relationships) in the set set return the entry interface typemap.entry<string, string> Entry = Iterator.next ();//Get the key value by means of GetValueString values = Entry.getvalue ();//Through method Getkey get keyString keys = Entry.getkey (); System.out.println ("key:"+ keys +"Value:"+ values); } }}
Operation Result:
The internal interface of the map interface entry
A entry interface is also defined inside the map interface, which is unique to the following methods:
1.boolean equals (Object o)
Compares the equality of the specified object to this item.
2.K GetKey ()
Returns the key corresponding to this item.
3. V GetValue ()
Returns the value corresponding to this item.
4.int Hashcode ()
Returns the hash code value for this mapping entry.
5.V SetValue (V value)
Replaces the value corresponding to this item with the specified value (optional action).
HashMap Collection Class
The underlying is a hash table data structure that the thread is not synchronized and can be stored in a null key, null value. To guarantee the uniqueness of the key, you need to override the Hashcode method, and the Equals method. elements are non-repeatable, no storage order
Storage principle of HashMap
The way HashMap stores elements is unordered, and the principle is the same as the HashSet collection.
When you store elements in HashMap, you first call the hashcode of the key to get the hash code value of the element, and then figure out where the data is stored in the hash table.
情况1:根据键的哈希码算出的位置目前没有任何元素存储,那么该元素可以直接添加。情况2: 根据键的哈希码算出的位置目前已经有了其他元素存储了,那么还会调用键的的equals方法再与这个位置的元素再比较一次。如果equals方法返回的是true,那么该元素不允许被添加,如果equals方法返回的是false,那么该元素允许添加。
TreeMap Collection Class
The keys can be sorted naturally, so they are stored in order. The bottom layer is a two-fork tree data structure. You can sort the keys in the map collection. You need to implement the comparable interface replication CompareTo method or a custom class to implement the comparator interface and create a comparator to sort the key values. return 0, to determine the uniqueness of the key.
TreeMap, TreeMap can sort the keys in the collection. How do I sort the keys?
method One : The elements themselves are comparable (natural sort)
As with TreeSet, it is necessary to let the object stored in the key position implement the comparable interface, overriding the CompareTo method, which means that the elements themselves are comparable, which is called the natural ordering of the elements is also called the default sort.
method Two : The container is of comparative
When the element itself is not comparable, or its own comparability is not required. At this point, you can make the container self-possessed. You need to define a class to implement the interface comparator, override the Compare method, and pass the subclass instance object of the interface as a parameter to the constructor of the TreeMap collection.
Note: When the comparable comparison mode and the comparator comparison method exist simultaneously, the comparison mode of comparator is the main;
Note: When overriding the CompareTo or compare method, you must compare the secondary conditions when you have to explicitly compare the primary conditions for equality. (assuming that the same person with the same name and age, if you want to sort people by age, how do people with the same age need to deal with it?) It is not possible to return 0 directly, expecting different names (people of different ages and different names). At this point you need to make a secondary conditional judgment (need to judge the name), only the name and age are equal to return 0.)
Storage principle of TreeMap
The principle is similar to TreeSet
1. When adding elements to TreeMap, if the key of the element is an attribute with a natural order, it is sorted by the natural order of the keys.
2. When adding elements to TreeMap, if the key of the data does not have a natural order, then the class that the key belongs to must implement the comparable interface. Define the rules of comparison in the CompareTo method.
3. When adding elements to TreeMap, if the key of the data does not have the nature of the natural order, and the class to which the key belongs does not implement the comparable interface, you can pass in a comparer object when creating the TreeMap object.
Note :
Set sets are elements that cannot be duplicated, and map keys are not duplicates.
How do I handle a repeating element if it is deposited?
Duplicate elements of set cannot be stored, and the Add method returns False
The duplicate key of the map overwrites the old key, and the Put method returns the value corresponding to the old key.
Customizing the TreeMap Collation
Or the comparator for the previous article.
/** * Customize a comparator class by ID * * @author mchenys * */ Public class mycomparator implements Comparator { /** * The rules for comparing two elements are written in the Compare method. * Returns a negative number if O1 is less than O2, returns a positive number if O1 is greater than O2, and returns 0 if they are equal; */ Public int Compare(Object O1, Object O2) {if(O1instanceofEMP && O2instanceofEMP) {EMP e1 = (EMP) O1; EMP e2 = (EMP) O2;returnE1.id-e2.id; }return 0; }}
Sort operations
/** * Sort the key for TreeMap collection by EMP ID * @author mchenys * */ Public class treemapsort { Public Static void Main(string[] args) {Mycomparator Comparator =NewMycomparator (); Treemap<emp, integer> map =NewTreemap<emp, integer> (comparator); Map.put (NewEMP (117,"haha", the),1); Map.put (NewEMP (222," very well", +),2); Map.put (NewEMP ( -,"hehe", -),3); Map.put (NewEMP ( -,"Roar", -),4); System.out.println (The elements of the collection are: "+ map); }}
Operation Result:
Collection Tool Class Collections
Common methods
1, sort the list collection.
Sort (list);
Sort (list,comaprator);
2, binary search for list, return to index position:
int BinarySearch (List,key);
int BinarySearch (list,key,comparator);
3, take the maximum or minimum value for the collection.
Max (Collection)
Max (Collection,comparator)
Min (Collection)
Min (collection,comparator)
4, reverses the list collection. Flips the elements in the collection.
Reverse (list);
5, the comparison method is forced to reverse.
Comparator Reverseorder ();
Comparator Reverseorder (Comparator);
6, the displacement of the position of the elements in the list collection.
Swap (list,x,y);
7, the element substitution is made on the list collection. If the replaced element does not exist, the original collection does not change.
ReplaceAll (list,old,new);
8, you can change the Unsynchronized collection to a synchronized collection.
Set Synchronizedset (set S)
Map Synchronizedmap (map m)
List synchronizedlist (List list)
Java Collection Architecture review (2)