The difference between hashmap,linkedhashmap,treemap

Source: Internet
Author: User
Tags iterable java util

The map is primarily used to store the health-value pairs, and the key is not allowed to repeat (overwriting is repeated), but allows the values to be duplicated.
Hashmap is the most commonly used map, it stores data according to the hashcode value of the key, can get its value directly according to the key, has the fast access speed, when traversing, obtains the data the order 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 synchronization is required, you can use the collections Synchronizedmap method to make the HashMap capable of synchronizing or using Concurrenthashmap.
Hashtable is similar to HashMap, which inherits from the dictionary class, except that it does not allow the record key or value to be null; it supports thread synchronization, which means that only one thread can write hashtable at any one time, so it also causes the hashtable to be slower to write.
Linkedhashmap preserves the order in which records are inserted, and when traversing linkedhashmap with iterator, the first record must be inserted first. You can also use the parameters in the construction to sort by the number of applications. The traversal will be slower than HashMap, but there is an exception, when the HashMap capacity is large, the actual data is small, the traversal may be slower than Linkedhashmap, because the Linkedhashmap traverse speed is only related to the actual data, and capacity-independent, And HashMap's traverse speed is related to his capacity.
TreeMap implements the Sortmap interface, it can save the record according to the key sort, the default is the key value of ascending order, you can also specify a sort of comparator, when using iterator traversal treemap, the resulting records are ordered.

In general, we use the most is the hashmap,hashmap inside the key value of the pair when it is taken out is random, it according to the hashcode value of the key to store data, according to the key can directly get its value, with fast access speed. HashMap is the best choice for inserting, deleting, and locating elements in a map.
The treemap takes out the sorted key-value pairs. But if you want to traverse the key in natural order or in a custom order , TreeMap is better.
Linkedhashmap is a subclass of HashMap, if you need to output the same order and input , then with LINKEDHASHMAP can be implemented, it can also be arranged in the order of reading, like the connection pool can be applied.

1. HashSet is implemented through HashMap, TreeSet is achieved through TREEMAP, except that set uses only the map key
2. A common feature of the key and set of map is the uniqueness of the collection. TreeMap is more a sort of feature.
3. Hashcode and equal () are used by HashMap because there is no need to sort, so just focus on positioning and uniqueness.
A. hashcode is used to calculate the hash value, and the hash value is used to determine the hash table index.
B. One index in the hash table holds a list, so the equal method is used to cycle through each object on the chain.
To actually locate the entry that corresponds to the key value.
C. When put, if the hash table is not located in the list, add a entry before the list, if it is located, replace the value in entry and return the old value
4. Because the treemap needs to be sorted, a comparator is required for the size comparison of the key values. Of course, it is also used to locate comparator.
A. Comparator can be specified when creating TreeMap
B. If the creation is not determined, then the Key.compareto () method is used, which requires key to implement the comparable interface.
C. TreeMap is implemented using the tree data structure, so you can use the Compare interface to complete the positioning.

Attention:
1. Collection does not have a get () method to get an element. Elements can only be traversed by iterator ().
2. Set and collection have identical interfaces.
3, List, you can use the Get () method to remove one element at a time. Use numbers to select one of a bunch of objects, get (0) .... (Add/get)
4, generally use ArrayList. Use LinkedList to construct stack stacks, queue queues.
5, map with put (K,V)/get (k), you can also use ContainsKey ()/containsvalue () to check if it contains a key/value.
HashMap will use the object's hashcode to quickly find the key.
* Hashing
The hash code is the transformation of the object's information into a unique int value, stored in an array.
We all know that the array lookup speed is the fastest in all storage structures. So, you can speed up lookups.

When a collision occurs, let the array point to multiple values. That is, the array generates a table of cassia at each location.
6, the element in the map, you can extract the key sequence, the value sequence alone.
Use Keyset () to extract the key sequence and generate a set for all keys in the map.
Use values () to extract the value sequence and generate a collection for all values in the map.
Why a build set, a Build collection? That's because key is always unique, and value allows repetition.

Ps:http://seaizon.iteye.com/blog/571101

Map,set,list, etc. set parsing in Java
In the Java util package there are two parent interfaces for all collections collection and map, their parent-child relationships:
Java.util
+collection This interface extends self---java.lang.iterable interface
+list interface
-arraylist class
-linkedlist class
-vector class This class is implemented synchronously.
+queue interface
+ not commonly used, not in this table.
+set interface
+sortedset interface
-treeset class
-hashset
+map interface
The-hashmap class (in addition to being unsynchronized and allowing null keys/values to be used, is roughly the same as Hashtable.)
-hashtable class This class is implemented synchronously and does not allow the use of NULL key values
+sortedmap interface
-treemap class
The following is a brief description of the many interfaces and classes: First of all, you can't start with arrays (array)
One, Array, Arrays
Array is the most efficient of all Java "storage and random access to a series of objects".
1.
High efficiency, but the capacity is fixed and cannot be changed dynamically.
One drawback of array is that it is not possible to determine how many elements are actually stored, and length simply tells us the capacity of the array.
2, Java has a arrays class, specifically used to manipulate the array.
The arrays has a set of static functions,
Equals (): Compares two arrays for equality. Array has the same number of elements, and all corresponding element 22 is equal.
Fill (): Fills the value into the array.
Sort (): Used to sort the array.
BinarySearch (): Looks for elements in a sorted array.
System.arraycopy (): Copy of Array.

Second, Collection, Map
If you do not know exactly how many objects you need to write your program, and you need to automatically expand capacity when you are running out of space, you need to use the Container class library, which is not applicable.
1. The difference between Collection and Map
The number of elements stored in the container is different.
collection type, with only one element per position.
Map type, holding Key-value pair, like a small database.
2, the purpose of JAVA2 container class library is "Save Object", it is divided into two categories, the respective sub-class relationship
Collection
--list: It ensures that element-specific order is maintained.
--arraylist/linkedlist/vector
--set: cannot contain duplicate elements
--hashset/treeset
Map
--hashmap
--hashtable
--treemap
MAP----A pair of "key-value pairs" objects, that is, its elements are paired objects, the most typical application is a data dictionary, and there are other widely used. In addition, map can return a set of all its keys and all its values, or a set consisting of its key-value pairs, and can also extend a multidimensional map like an array, as long as each "value" of the key-value pairs in the map is a map. Collection.

Collection 1. iterators

An iterator is a design pattern that is an object that can traverse and select objects in a sequence, and the developer does not need to know the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because they are less expensive to create.

The iterator functionality in Java is relatively simple and can only be moved one way:

(1) Use method iterator () requires the container to return a iterator. The first time you call Iterator's next () method, it returns the first element of a sequence. Note: The iterator () method is an Java.lang.Iterable interface that is inherited by collection.


(2) Use Next () to get the next element in the sequence.

(3) Use Hasnext () to check if there are elements in the sequence.

(4) use remove () to delete the newly returned element of the iterator.

Iterator is the simplest implementation of Java iterators, with more functionality for the listiterator of list design, which can traverse the list in two directions or insert and delete elements from a list.

function method of 2.List

List (interface): Order is the most important feature of the list; It ensures that elements are maintained in a specific order. The list adds a number of methods to collection, allowing you to insert and remove elements to the middle of the list (only recommended for linkedlist use). A list can generate Listiterator, which can be used to traverse a list in two directions or to insert and delete elements from the middle of a list.

ArrayList: A list implemented by an array. It allows for fast 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 backward, rather than to insert and delete elements, as this is much larger than the linkedlist overhead.

LinkedList: Lists implemented by the list. Sequential access is optimized to insert and delete in the middle of the list with little overhead and random access is relatively slow (available ArrayList instead). It has methods AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), Removelast (), and these methods (not defined in any interface or base class) Enables LinkedList to be used as stacks, queues, and bidirectional queues.

function method of 3.Set

Set (interface): Each element that is stored in the set must be unique, which is also different from the list, because set does not save duplicate elements. The object that joins the set must define the Equals () method to ensure the uniqueness of the object. The set has exactly the same interface as the collection. The set interface does not guarantee the order in which elements are maintained.

Hashset:hashset can quickly locate an element, and the object stored in HashSet must define HASHCODE ().

TreeSet: The set of the hold order, the bottom is the tree structure. Use it to extract ordered sequences from the set.

Linkedhashset: has hashset query speed, and internally uses the chain list to maintain the order of elements (the Order of insertions). The result is displayed in the order in which the elements are inserted when iterating through the set using Iterators.

HashSet uses a hash function to sort the elements, which is specifically designed for quick queries, treeset the data structure of the red-black tree, and linkedhashset internally uses hashing to speed up the query, while maintaining the order of the elements using the linked list, Makes it seem that elements are saved in the order in which they are inserted. It is important to note that when generating your own classes, the set needs to maintain the order in which the elements are stored, so implement the comparable interface and define the CompareTo () method.
function method of 4.Map
Java defines an interface java.util.Map for the mappings in the data structure; it has four implementation classes, namely HashMap Hashtable Linkedhashmap and TreeMap
Map is primarily used to store health-value pairs, which are given a value based on the key, so the key is not allowed to repeat, but the allowed value repeats.
Hashmap 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 fast access speed. 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 synchronization is required, you can use the collections Synchronizedmap method to make the HashMap capable of synchronizing.
Hashtable is similar to HashMap, except that it does not allow the record key or value to be null; it supports thread synchronization, which means that only one thread can write Hashtable at any one time, so it also causes the Hashtale to write slower.
Linkedhashmap saves the order in which records are inserted, and when traversing linkedhashmap with iterator, the first record must be inserted first. It is slower than hashmap when traversing.
TreeMap is able to sort its saved records by key, by default in ascending order, or by specifying a sort comparer, and when traversing treemap with iterator, the resulting records are sorted out.

3. Other Features
* List,set,map holds objects as Object type.
* Collection, List, Set, map are all interfaces and cannot be instantiated.
ArrayList, vectors, HashTable, and HashMap are inherited from them, and these can be instantiated.
* The vector container knows exactly what type of object it holds. Vectors do not perform boundary checks.

Third, collections
Collections is a helper class for the collection class. Provides a series of static methods for searching, sorting, threading, and so on for various collections.
A class--arrays equivalent to a similar operation on an array.
For example, Collections.max (Collection coll); Take the largest element in the Coll.
Collections.sort (list list); Sort elements in List
Iv. How to choose?
1, the difference between the container class and the array, playable
* The container class can only hold object references (pointers to objects), rather than copy the object information to a position in a sequence.
* Once the object is placed in the container, the object's type information is lost.
2.
* In various lists, the best practice is to use ArrayList as the default choice. When inserting and deleting frequently, use LinkedList ();
Vector is always slower than ArrayList, so try to avoid it.
* In various sets, hashset is usually better than hashtree (INSERT, find). Use TreeSet only if you need to produce a sorted sequence.
The only reason for the existence of Hashtree: the ability to maintain the ordering state of its elements.
* In a variety of maps
The HashMap is used for quick lookups.
* When the number of elements is fixed, use array, because array efficiency is the highest.
Conclusion: The most commonly used is arraylist,hashset,hashmap,array. Also, we will find a pattern, which is sorted by treexxx.

The difference between hashmap,linkedhashmap,treemap (turn)

Related Article

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.