Solved

collection output issue

Posted on 2017-03-02
9
58 Views
Last Modified: 2017-03-09
 

 
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
 
public class MyHashMapEntrySet3 {
 
    public static void main(String arg[]){
      HashMap hm = new HashMap<Integer, String>();
    	//HashMap hm = new TreeMap<String, String>();
    	//HashMap hm = new LinkedHashMap<String, String>();
        //add key-value pair to hashmap
        hm.put(3, "C");
        hm.put(1, "A");
        hm.put(2, "B");
        //hm.put(3, "C");
        System.out.println(hm);
        //getting value for the given key from hashmap
       /* Set<Entry<String, String>> entires = hm.entrySet();
        for(Entry<String,String> ent:entires){
            System.out.println(ent.getKey()+" ==> "+ent.getValue());*/
       //d }
    }
}

Open in new window


{1=A, 2=B, 3=C}


i wonder how i got above sorted output based on key all the time first 1 then 2 then 3 key set? please advise
0
Comment
Question by:gudii9
  • 4
  • 3
  • 2
9 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 42031683
0
 
LVL 7

Author Comment

by:gudii9
ID: 42031883
What is the answer for this question I could not find there
0
 
LVL 7

Author Comment

by:gudii9
ID: 42031898
you mean below
The ordering is preserved in that particular case since the hash code of 1 is 1, 2 is 2 etc.

http://stackoverflow.com/questions/2817695/how-does-java-order-items-in-a-hashmap-or-a-hashtable



HashMap stores the values using the unique hash-value generated using a part of the key

which part of the key it uses
how to see Integer 1 hashcode in documentation where it is preserving order?
same how to see String 1 hashcode in documentation where it is messing order
0
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 10

Accepted Solution

by:
Jeffrey Dake earned 250 total points
ID: 42032056
With the maps you really have to look at the contracts that they guarantee. A hashmap, just like a hashset may give you the same order but it is not guaranteed. To have it sorted you really need to use the tree map, that guarantees the order based on a comparator.
0
 
LVL 27

Assisted Solution

by:rrz
rrz earned 250 total points
ID: 42032405
From the documentation,
http://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html   
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
 
Since the class uses the same algorithm each time, the results will probably be the same each time you run your program. But, this behavior is not guaranteed.  
Also from the documentation,
http://docs.oracle.com/javase/8/docs/api/java/util/Map.html   
The order of a map is defined as the order in which the iterators on the map's collection views return their elements.

But, there no guarantees.  
The important feature of Map is the time it takes to "get" the value that is associated with a particular key. If we have a lot of data in the Map, then using HashMap will be faster than using one of the other Maps that do guarantee order.
0
 
LVL 7

Author Comment

by:gudii9
ID: 42032647
i am getting same result many many times consistently which makes me believe it is predictable
0
 
LVL 27

Expert Comment

by:rrz
ID: 42032665
i am getting same result many many times
I see the same behavior. But, what if we move our code to a different environment? What if we run our code with different Java version?    We could see different results.
0
 
LVL 7

Author Comment

by:gudii9
ID: 42032709
make sense
0
 
LVL 10

Expert Comment

by:Jeffrey Dake
ID: 42032729
Also if the hashing function underneath changed you could get different results.  That's why the ordered sets and maps use comparable objects so the order can always be guaranteed.
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Generate Unique ID in VB.NET 21 99
junit example issue 2 22
Github api to fetch the number of collaborators in a git repo 1 25
Ruby or Python 7 42
Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question