Javase Getting Started learning the map interface of 37:java set framework and its implementation class HashMap and TreeMap

Source: Internet
Author: User

A map interface

Each member method in the map interface consists of a keyword (key) and a value (value). The map interface does not inherit directly from the collection interface because

It is packaged as a set of "key-value" objects, and no duplicate keys appear in the collection of map interfaces, because each key can only be

A member element corresponds to.

The map interface defines a method that stores the key (key)-value mapping pair. The class that implements the map interface is used to store key-value pairs. The Map interface contains

A keyset () method that returns a set set of all keys in a map.

the features of the map interface are:

1) The map interface provides a mapping relationship where elements are stored as key-value pairs (key-value), the ability to quickly find value based on key.

2) The key values in map exist as object instances of type entry. Key (key value) is not repeatable, value can be.

3) Each key can be mapped to at most one value.

4) The Map interface provides methods for returning a collection of key values, a collection of value values, and a collection of entry (key-value pairs), respectively.

5) Map also supports generics, in the form of:map<k,v>.

6) Key-value pairs stored in the map interface are identified by key, so the key value cannot be duplicated, i.e. any two key of the same map object is passed by equals ()

The method comparison always returns false.

The methods defined in the map interface are:


There are three main implementations of the map interface: HashMap, TreeMap, and Hashtable. In general, the most we use is

HashMap, HashMap is the best choice for inserting, deleting, and locating elements in a map. But if you want to traverse in natural order or custom order

Key, then TreeMap will be better. If you need the output in the same order as the input. So with the HashMap subclass Linkedhashmap can be implemented,

It can also be arranged in reading order.

two HashMap implementation class

The HashMap class is the most commonly used map, which stores data according to the hashcode value of the key, which can be obtained directly from the key, with a quick

Ask speed, when traversing, the order in which the data is obtained is completely random. HashMap allows a maximum of one record's key to be null, allowing multiple records to have a value of

Null; HashMap does not support thread synchronization, where multiple threads can write HashMap at any one time, and may result in inconsistent data. If you need

Synchronization, you can use the Synchronizedmap () method of the Collections collection class to enable the HashMap class to have the ability to synchronize.

Because HashMap can not be duplicated, so hashmap only a pair of Key-value value is null, but there are countless many key-value to

The value is null.

HashMap overrides the ToString () method method to always return a string in the following format: {key1 = Value1,key2 = value2 ...}

HashMap two keys equal to the standard is: two key by EQUASL () method to compare the return ture, two key hashcode value is equal.

features of HashMap:

1) HashMap is an important implementation class of map and the most common one, based on hash table implementation.

2) The entry objects in the HashMap are unordered.

3) Both the key and value values can be null, but a hashmap can have only one mapping with a key value of NULL (the key value cannot be duplicated).

HashMap methods of implementing classes:


Instance:

Import java.util.*;p Ublic class Testhashmap {public static void main (string[] args) {map<dog, integer> hashMap = new Hashmap<dog, integer> ();D og d1 = new Dog ("Red");D og d2 = new Dog ("Black");D og d3 = new Dog ("white");D og d4 = new do G ("white"); Hashmap.put (d1, hashmap.put); Hashmap.put (D3, 5); Hashmap.put (D4, 20); Print sizeSystem.out.println (Hashmap.size ()); Loop Hashmapfor (Map.entry<dog, integer> entry:hashMap.entrySet ()) {System.out.println (Entry.getkey ()). ToString () + "-" + entry.getvalue ());}}} Class Dog {String color; Dog (String c) {color = c;} Public String toString () {return color + "dog";}}

Operation Result:


Look, we mistakenly added two "white dogs", but HashMap accepted it, which is strictly pointless, because now "white

The number of dogs "has been confused.

The modified Dog class looks like this:

Class Dog {    String color;     Dog (String c) {        color = c;    }     public boolean equals (Object o) {        return (DOG) o). color = = This.color;    }     public int hashcode () {        return color.length ();    }     Public String toString () {            return color + "dog";    }}

Operation Result:


The reason is that HashMap does not run two identical elements as keys. If not overridden, the hashcode () and the object class implementation will be used.

The Equals () method, the default Hashcode () method, returns a different integer for each different object; the default Equals () method compares only two references

Whether to point to the same actual object.

three TreeMap implementation class

The map interface derives a SortedMap sub-interface and TreeMap implements the class for it. Similar to the TreeSet sort, TreeMap is also based on a red-black tree

All keys in the treemap are sorted to ensure that all key-value pairs in the treemap are in an orderly state. TreeMap two methods of sorting:

1) Natural sort:all keys of TreeMap must implement comparable interface, and all keys should be objects of the same class, otherwise it will throw

Classcastexcepiton exception.

2) Custom sort: When you create TREEMAP, you pass in a comparator object that is responsible for sorting all the keys in the TreeMap. Adopt a fixed

The comparable interface is not required for the key of the map when making the order.

The criteria for determining the equivalent of two keys in TreeMap is also two keys to return true through the Equals () method, while the CompareTo () method returns

0,treemap that the two keys are equal.

If you use a custom class as a key for TreeMap, you should re-match the equals of the class (0 method and CompareTo () method when there should be a consistent return knot

The result: Two keys are compared by the Equals () method to return True when they are compared by the CompareTo () method should return 0. If the Equals () method

The return result of the CompareTo () method is inconsistent or there is a discrepancy between the rules of the TREEMAP and the map interface (when the Equals () method returns True, but

CompareTo () method comparison does not return 0 o'clock), or treemap processing performance is decreased (when the CompareTo () method compares return 0 when

Equals () method comparison does not return True when).

TreeMap implements the method:




Instance:

Import java.util.*;p Ublic class Testtreemap {public static void main (string[] args) {Dog D1 = new Dog ("Red");D og d2 = new Dog ("Black");D og d3 = new Dog ("white");D og d4 = new Dog ("white"); Map<dog, integer> treeMap = new Treemap<dog, integer> (); treemap.put (D1); Treemap.put (D2, 15); Treemap.put (D3, 5); Treemap.put (D4, 20); For (Map.entry<dog, integer> entry:treeMap.entrySet ()) {System.out.println (Entry.getkey () + "-" + entry.getvalue ());}}} Class Dog {String color; Dog (String c) {color = c;} public boolean equals (Object o) {return (DOG) o). color = = This.color;} public int hashcode () {return color.length ();} Public String toString () {return color + "dog";}}

Operation Result:


Since TreeMap is sorted by key, the key object must be able to be compared to another object, so the comparable interface must be implemented. When

However, you can also use the string object as the key because the string class already implements the comparable interface.

Below, we modify the code of the Dog class to implement the comparable interface:

Import java.util.*;p Ublic class Testtreemap {public static void main (string[] args) {Dog D1 = new Dog ("red", +);D og d2 = New Dog ("Black");D og d3 = new Dog ("White", "ten");D og d4 = new Dog ("white", 10); Map<dog, integer> treeMap = new Treemap<dog, integer> (); treemap.put (D1); Treemap.put (D2, 15); Treemap.put (D3, 5); Treemap.put (D4, 20); For (Map.entry<dog, integer> entry:treeMap.entrySet ()) {System.out.println (Entry.getkey () + "-" + entry.getvalue ());}}} Class Dog implements comparable<dog>{string color;int size; Dog (String c, int s) {color = C;size = s;} public String toString () {return color + "dog";} @Overridepublic int CompareTo ( Dog o) {return  o.size-this.size;}}

Operation Result:


This is the result of sorting based on the key object, where we use size (size) to compare dog. If we put "dog D4 = new Dog" ("white"

, 10); " This line of code is replaced by "dog D4 = new Dog" ("white", 40); " Then, the result of the execution is:


The reason is that TreeMap uses the CompareTo () method to compare key objects, and different size is considered a different dog.

There is so much to say about the map interface and its implementation class.



Javase Getting Started learning the map interface of 37:java set framework and its implementation class HashMap and TreeMap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.