Similarities and differences between HashMap and Linkedhashmap in Java

Source: Internet
Author: User



In a nutshell: The big difference between the two is that HASHMAP does not guarantee the order of the data put in, while Linkedhashmap guarantees the order of the data put in. In other words, the order in which the data is added HashMap and the order in which the data is traversed is not necessarily, while linkedhashmap guarantees what the data order is when it is added and what the data order is in the traversal.
For example, if you add elements sequentially and sequentially in HashMap: 1,2,3,4,5, the order in which the output is to traverse HashMap may be: 3,2,1,4,5.
However, if you add elements sequentially and sequentially in Linkedhashmap: 1,2,3,4,5, the order in which the output is to be added is the original order of the add operation: 1,2,3,4,5.
Code Demo:

Import Java.util.hashmap;import java.util.linkedhashmap;/* * Add 10 elements, then output, compare HashMap and Linkedhashmap output results in similarities and differences.  * */public class Map {public static void main (string[] args) {hashmap<string, integer> map1 = new hashmap<string, Integer> (); linkedhashmap<string, integer> map2 = new linkedhashmap<string, integer> (); String key = "key"; for (int i = 0; i < i++) {Map1.put (key + I, I); Map2.put (key + I, i);} System.out.println ("HashMap:"); for (String K:map1.keyset ()) {System.out.println (k + "+ map1.get (k));} System.out.println (); System.out.println ("Linkedhashmap:"); for (String K:map2.keyset ()) {System.out.println (k + "+ map2.get (k));}}}

Output Result:

HashMap:key4 4key3 3key6 6key5 5key0 0key2 2key1 1key8 8key7 7key9 9LinkedHashMap:key0 0key1 1key2 2key3 3key4 4key5 5key6 6key7 7key8 8key9 9


Similarities and differences between HashMap and Linkedhashmap in Java

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.