Map, set, list, and so on.

Source: Internet
Author: User
Tags comparable iterable java util

Map, set, list, and so on.

Preface:
Today, I think of a set of map, set, list, and other materials, so I took some notes and provided them for your reference and future review.

First, Map is mainly used to store the key-value pairs and obtain values based on the key. Therefore, duplicate keys are not allowed (repeated overwrites), but repeated values are allowed. The most common map types are as follows:

Hashmap: it is the most commonly used Map. It stores data based on the HashCode value of the key, and can directly obtain its value based on the key, with fast access speed and time, the order in which data is obtained is completely random. HashMap allows a maximum of Null keys for one record, and Null values for multiple records. HashMap does not support thread synchronization, that is, multiple threads can write HashMap simultaneously at any time; data inconsistency may occur. If synchronization is required, you can use the synchronizedMap method of Collections to synchronize HashMap or use ConcurrentHashMap.

Hashtable: similar to HashMap, It inherits from the Dictionary class. The difference is that it does not allow null keys or values to be recorded. It supports thread synchronization, at any one time point, only one thread can write Hashtable, which also causes the write speed of Hashtable to be slow.

LinkedHashMap: stores the record insertion sequence. When Iterator is used to traverse LinkedHashMap, the first record must be inserted first. You can also use parameters to sort the records by application times during construction. It is slower than HashMap during traversal, but in some cases, when the HashMap capacity is large and the actual data is small, the traversal may be slower than LinkedHashMap, because the traversal speed of LinkedHashMap is only related to the actual data and has nothing to do with the capacity, and the traversal speed of HashMap is related to its capacity.

TreeMap: implements the SortMap interface, which can sort the records stored by the key. By default, It is the sort of key values in ascending order. You can also specify the sort comparator. When you use Iterator to traverse the TreeMap, the obtained records are sorted in ascending order.

Generally, HashMap is used most often. The key-value pairs stored in HashMap are random when they are retrieved. It stores data based on the key's HashCode value, you can directly obtain its value based on the key, with fast access speed. HashMap is the best choice for inserting, deleting, and locating elements in a Map.

TreeMap obtains the sorted key-value pairs. However, if you want to traverse key values in the natural or custom order, it will be better for TreeMap.

LinkedHashMap is a subclass of HashMap. If the output sequence is the same as the input sequence, you can use LinkedHashMap to implement it. It can also be arranged in the read order, as it can be applied in the connection pool.

 

 

1. HashSet is implemented through HashMap, and TreeSet is implemented through TreeMap, except that Set only uses the Map key.

2. The key and Set of Map have a common feature that is the uniqueness of the Set. TreeMap has an additional sorting function.

3. hashCode and equal () are used by HashMap. Because no sorting is required, you only need to pay attention to location and uniqueness.

A. hashCode is used to calculate the hash value, and the hash value is used to determine the index of the hash table.
B. An index in the hash table stores a linked list. Therefore, you must use the equal method to cyclically compare each object in the chain.
To locate the Entry corresponding to the key value.
C. put: If the hash table is not located, add an Entry in front of the linked list. If it is located, replace the value in the Entry and return the old value.

4. Because TreeMap needs to be sorted, a Comparator is required to compare the size of the key value. Of course, it is also located using Comparator.
A. Comparator can specify
B. If it is not determined during creation, the key. compareTo () method will be used, which requires that the key must implement the Comparable interface.
C. TreeMap is implemented using the Tree data structure, so you can use the compare interface to complete the positioning.

 

 

Note:
1. Collection does not have the get () method to obtain an element. You can only use iterator () to traverse elements.

2. Set and Collection have the same interface.

3. List. You can use the get () method to retrieve an element at a time. Use numbers to select one of a bunch of objects, get (0 ).... (Add/get)

4. ArrayList is generally used. Use the queue list to construct the stack and queue.

5. Map uses put (k, v)/get (k) and containsKey ()/containsValue () to check whether a key/value exists.
HashMap uses the hashCode of the object to quickly find the key.
* Hashing
The hash code transforms the object information to form a unique int value, which is stored in an array.
We all know that the array search speed is the fastest in all storage structures. Therefore, the search can be accelerated.

When a collision occurs, let the array point to multiple values. That is, an orders table is generated at each position of the array.

6. Elements in Map can be extracted separately from the key sequence and value sequence.
Use keySet () to extract the key sequence and generate a Set for all the keys in the map.
Use values () to extract the value sequence and generate a Collection for all values in the map.
Why does one generate a Set and one generate a Collection? That's because the key is always unique and the value can be repeated.

 

Followed by map, set, list and other java integrated parsing:

In the JAVA util package, there are two sets of parent Interface Collection and Map. Their parent-child relationship:
Java. util
+ Collection: extends: java. lang. Iterable
+ List Interface
-ArrayList class
-Shortlist class
-The Vector class implements synchronization.
+ Queue Interface
+ Not commonly used. This is not a table.
+ Set Interface
+ SortedSet Interface
-TreeSet class
-HashSet
+ Map interface
-HashMap class (except for not synchronizing and allowing the use of null keys/values, it is roughly the same as Hashtable .)
-The Hashtable class is synchronous and the null key value cannot be used.
+ SortedMap Interface
-TreeMap class
The following is a simple description of many interfaces and classes: first, let's not go over arrays)
I. Array, Arrays
Array is the most efficient method for Java's "Storage and random access to a series of objects.
1. High efficiency, but the capacity is fixed and cannot be changed dynamically.
Another disadvantage of array is that it cannot determine the actual number of elements in the array. length only tells us the array capacity.

2. There is an Arrays class in Java that is used to operate Arrays.
Arrays has a set of static functions,
Equals (): checks whether two arrays are equal. Array has the same number of elements, and all corresponding elements are equal to each other.
Fill (): Enter the value in array.
Sort (): used to sort arrays.
BinarySearch (): Search for elements in the sorted array.
System. arraycopy (): copying an array.

Ii. Collection and Map
If you do not know how many objects are needed when writing a program and need to automatically expand the capacity when the space is insufficient, you need to use the container class library. array is not applicable.
1. Differences between Collection and Map
The number of elements stored in each container is different.
Collection type, each location has only one element.
Map type, holding key-value pair, like a small database.

2. the Java2 container class library is used to "save objects". It is divided into two categories, each of which has its own subclass relationship.
Collection
-- List: it ensures that the specific sequence of elements is maintained.
-- ArrayList/Vector list/Vector
-- Set: duplicate elements cannot be contained.
-- HashSet/TreeSet
Map
-- HashMap
-- HashTable
-- TreeMap
Map ---- A key-Value Pair object composed of a pair, that is, its elements are paired objects. The most typical application is data dictionary, and there are other extensive applications. In addition, Map can return a Collection composed of all its values and a Set composed of all its key-value pairs, or a Set composed of its key-value pairs. It can also expand multi-dimensional Map like an array, you only need to make each "value" of the key-value pair in the Map a Map.

1. iterator under Collection

An iterator is a design pattern. It is an object that can traverse and select objects in a sequence. Developers do not need to understand the underlying structure of the sequence. An iterator is usually called a "lightweight" object because it is easy to create.

The Iterator function in Java is relatively simple and can only be moved one way:

(1) The method iterator () requires the container to return an Iterator. When the next () method of Iterator is called for the first time, it returns the first element of the sequence. Note: The iterator () method is a java. lang. Iterable interface inherited by Collection.


(2) Use next () to obtain the next element in the sequence.

(3) Use hasNext () to check whether there are any elements in the sequence.

(4) use remove () to delete the elements returned by the iterator.

Iterator is the simplest implementation of the Java Iterator. The ListIterator designed for List has more functions. It can traverse the List in two directions, or insert and delete elements from the List.

2. Functional methods of List

List (interface): Order is the most important feature of List. It ensures that the order of elements is maintained. List adds many methods to the Collection so that you can insert and remove elements to the List (only recommended for using the sort List ). A List can generate ListIterator, which can be used to traverse the List in two directions, or to insert and delete elements from the List.

ArrayList: List implemented by arrays. It allows fast and Random Access to elements, but it is slow to insert and remove elements into the List. ListIterator should only be used to traverse the ArrayList from the back to the back, rather than to insert and delete elements, because this is much more overhead than the aggregate list.

List: List implemented by the List. The sequential access is optimized, with little overhead for inserting and deleting data into the List. Random Access is relatively slow (can be replaced by ArrayList ). It has methods such as addFirst (), addLast (), getFirst (), getLast (), removeFirst (), removeLast (), these methods (not defined in any interface or base class) allow the consumer list to be used as a stack, queue, and bidirectional queue.

3. Functions and methods of Set

Set (interface): Each element stored in the Set must be unique, which is different from the List, because the Set does not store duplicate elements. Objects added to the Set must define the equals () method to ensure the uniqueness of the Object. Set has the same interface as Collection. The Set interface does not guarantee the order of maintenance elements.

HashSet: A HashSet can quickly locate an element. The object stored in the HashSet must define hashCode ().

TreeSet: Set that maintains the order. The bottom layer is the tree structure. It can be used to extract ordered sequences from the Set.

LinkedHashSet: query speed with a HashSet, and internal use of the linked list to maintain the order of elements (insert order ). When you use the iterator to traverse the Set, the result is displayed in the order of element insertion.

HashSet uses the hash function to sort elements, which is specially designed for fast query. TreeSet uses the data structure of the red/black tree to sort elements; hashset uses hashes internally to speed up query, and maintains the order of elements using the linked list so that the elements are saved in the order of insertion. Note that when generating your own class, Set needs to maintain the storage sequence of the elements. Therefore, you must implement the Comparable interface and define the compareTo () method.
4. Functional methods of Map
Java defines an interface java. util. Map for ing in the data structure. It has four implementation classes: HashMap Hashtable LinkedHashMap and TreeMap.
Map is mainly used to store key-value pairs and obtain values based on keys. Therefore, duplicate keys are not allowed, but repeated values are allowed.
Hashmap is the most commonly used Map. It stores data based on the HashCode value of the key, and can directly obtain its value based on the key, with fast access speed. HashMap allows a maximum of Null keys for one record, and Null values for multiple records. HashMap does not support thread synchronization, that is, multiple threads can write HashMap simultaneously at any time; data inconsistency may occur. If synchronization is required, use the synchronizedMap method of Collections to synchronize HashMap.
Hashtable is similar to HashMap. The difference is that it does not allow record keys or empty values; it supports thread synchronization, that is, only one thread can write Hashtable at any time, as a result, Hashtale writes slowly.
LinkedHashMap stores the record insertion sequence. When Iterator is used to traverse LinkedHashMap, the first record must be inserted first. It will be slower than HashMap during traversal.
TreeMap can sort the records stored by the key. By default, the record is sorted in ascending order. You can also specify a comparator. When you use Iterator to traverse the TreeMap, the obtained records are sorted in ascending order.

The following is the comparison test code:

Public class TestMap {/*** initialize a Map * @ param map */public static void init (Map map) {if (map! = Null) {String key = null; for (int I = 5; I> 0; I --) {key = new Integer (I ). toString () + ". 0 "; map. put (key, key. toString (); // keys in the Map are not repeated. If two records with the same key value are inserted, the inserted record overwrites the map of the first inserted record. put (key, key. toString () + "0") ;}}/ *** output a Map * @ param map */public static void output (Map map) {if (map! = Null) {Object key = null; Object value = null; // use the Iterator to traverse the Map key. Iterator it = map according to the key value. keySet (). iterator (); while (it. hasNext () {key = it. next (); value = map. get (key); System. out. println ("key:" + key + "; value:" + value) ;}// or use the iterator to traverse the Map record Map. entry Map. entry entry = null; it = map. entrySet (). iterator (); while (it. hasNext () {// a Map. entry indicates a record entry = (Map. entry) it. next (); // you can obtain Key and value // System. out. println ("key:" + entry. getKey () + "; value:" + entry. getValue () ;}}/ *** determines whether a map contains a key * @ param map * @ param key * @ return */public static boolean containsKey (Map map, object key) {if (map! = Null) {return map. containsKey (key);} return false ;} /*** determine whether map contains a value * @ param map * @ param value * @ return */public static boolean containsValue (Map map, Object value) {if (map! = Null) {return map. containsValue (value);} return false;}/*** demonstrate HashMap */public static void testHashMap () {Map myMap = new HashMap (); init (myMap ); // The HashMap key can be null myMap. put (null, "ddd"); // The HashMap value can be null myMap. put ("aaa", null); output (myMap);}/*** demonstrate Hashtable */public static void testHashtable () {Map myMap = new Hashtable (); init (myMap); // The Key of Hashtable cannot be null // myMap. put (null, "ddd ");/ /Hashtable value cannot be null // myMap. put ("aaa", null); output (myMap);}/*** demonstrate LinkedHashMap */public static void testLinkedHashMap () {Map myMap = new LinkedHashMap (); init (myMap); // The LinkedHashMap key can be null myMap. put (null, "ddd"); // The LinkedHashMap value can be null myMap. put ("aaa", null); output (myMap);}/*** demo TreeMap */public static void testTreeMap () {Map myMap = new TreeMap (); init (myMap); // The TreeMap key cannot be null // MyMap. put (null, "ddd"); // The TreeMap value cannot be null // myMap. put ("aaa", null); output (myMap);} public static void main (String [] args) {System. out. println ("using HashMap"); TestMap. testHashMap (); System. out. println ("Hashtable"); TestMap. testHashtable (); System. out. println ("LinkedHashMap"); TestMap. testLinkedHashMap (); System. out. println ("using TreeMap"); TestMap. testTreeMap (); Map myMap = new HashMap (); TestM Ap. init (myMap); System. out. println ("initialize a new Map: myMap"); TestMap. output (myMap); // clear Map myMap. clear (); System. out. println ("after myMap is clear, is myMap empty? "+ MyMap. isEmpty (); TestMap. output (myMap); myMap. put ("aaa", "aaaa"); myMap. put ("bbb", "bbbb"); // determines whether a Map contains a key or a value System. out. println ("myMap contains the key aaa? "+ TestMap. containsKey (myMap," aaa "); System. out. println (" myMap contains aaaa? "+ TestMap. containsValue (myMap, "aaaa"); // deletes the record myMap in the Map based on the key. remove ("aaa"); System. out. println ("after the deletion key aaa, myMap contains the key aaa? "+ TestMap. containsKey (myMap, "aaa"); // gets the number of Map records System. out. println ("number of records contained in myMap:" + myMap. size ());

  

3. Other features
* List, Set, and Map objects are regarded as Object types.
* Collection, List, Set, and Map are all interfaces and cannot be instantiated.
The ArrayList, Vector, HashTable, and HashMap inherited from them are concrete classes, which can be instantiated.
* The vector container knows exactly the type of the object it holds. Vector does not perform boundary check.

Iii. Collections
Collections is a help class for the Collection class. Provides a series of static methods for searching, sorting, and thread-based operations on various sets.
It is equivalent to Arrays, a class that performs similar operations on Arrays.
For example, Collections. max (Collection coll); obtains the largest element in coll.
Collections. sort (List list); sorts the elements in the list.


4. How to choose?
1. Differences between the container class and Array
* The container class can only hold the object reference (pointer to the object), instead of copying the object information to a certain position in the series.
* Once an object is placed in a container, the type information of the object is lost.
2,
* Among various Lists, it is best to use ArrayList as the default choice. Use the sort list () When insertion or deletion is frequent ();
Vector is always slower than ArrayList, so avoid using it whenever possible.
* In various Sets, HashSet is generally better than HashTree (insert and search ). TreeSet is used only when a sorted sequence is generated.
The only reason for the existence of HashTree is that it can maintain the sorting status of its elements.
* In various Maps
HashMap is used for quick search.
* When the number of elements is fixed, Array is used because the Array efficiency is the highest.

 
Conclusion: ArrayList, HashSet, HashMap, and Array are commonly used. In addition, we will also find a rule in which TreeXXX is sorted.

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.