Collection (Map)

Common implementation classes of Map interface: HashMap, TreeMap, Properties

HashMap

HashMap is the most frequently used implementation class

Null keys and null values ​​are allowed, like HashSet, the order of the map is not guaranteed

The standard for HashMap to judge the equality of a key is: the two keys return true through the equals method, and the hashCode value is also equal

The standard for HashMap to judge the equality of two values ​​is: the two values ​​return true through the equals method  

 

LinkedHashMap

LinkedHashMap is a subclass of HashMap, consistent with linkedHashSet, linkedHashMap can maintain the iteration order of the map, and the iteration order is consistent with the key-value insertion order

 

TreeMap

When TreeMap stores key-value pairs, it needs to be sorted according to key-value pairs. Treemap can ensure that all key-value pairs are in order.

The key sorting of TreeMap:

Natural sorting: All keys of TreeMap implement the Comparable interface, and all keys are objects of the same class, otherwise an exception will be thrown

Custom sorting: When creating a TreeMap, a Comparator object is passed in, which loads all the keys of the TreeMap to be sorted. At this time, the Map does not need to implement the Comparable interface.

The criteria for TreeMap to judge the equality of two keys: the two keys return 0 through the compareTo method or the compare() method

If you use a custom class as the key of TreeMap, the class you belong to needs to override the equals and hasCode methods, and equals returns true, hasCode returns 0

 

Hashtable

Thread safety, null is not allowed as key and value, the order of key-value cannot be guaranteed, and the method of judging whether key and value are the same is consistent with HashMap

 

 

Properties

A subclass of Hashtable for working with properties files

Properties pros = new Properties();
pros.load(new FileInputStream("jdbc.properties"));
String user = pros.getProperty("user");
System.out.println(user);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325554201&siteId=291194637