Dumping HashMAp

S

Sridhar

Consider the following snippet to display the contemts of a HashMap in
a sequential manner.

//temp2 is a hashmap
Set set2=temp2.entrySet();
Iterator iHash2=set2.iterator();

while(iHash2.hasNext()){
Map.Entry me2= (Map.Entry) iHash2.next();
System.out.println(me2.getKey());
}

I printed the order in which the elements were entered in the HashMap
and later printed the hashMap using the above algorithm... both are
different.... Any idea why??

I'm just printing the keys here. During insertion the order followed
for the key is
r1,s3,s2,s1

but when i print the hashmap the order is:
s2,s3,r1,s1

Since i need to use it sequentially later in the application, the order
is very important. I cant sort the hashmap too as keys have no relation
whatsoever.

Any pointers??
 
I

Ingo R. Homann

Hi,
I printed the order in which the elements were entered in the HashMap
and later printed the hashMap using the above algorithm... both are
different.... Any idea why??

Because HashMap does not say anything about the order! (Are you sure,
you understand what a HashMap does? If not, do not use it, especially
not with own objects, because you may be surprised about different
issues as well!)

Perhaps, SortedMap / TreeMap can help you. Otherwise, a
(Array-/Linked)List might be what you are looking for.

Ciao,
Ingo
 
A

Ace

Try LinkedHashMap
Hi,


Because HashMap does not say anything about the order! (Are you sure,
you understand what a HashMap does? If not, do not use it, especially
not with own objects, because you may be surprised about different
issues as well!)

Perhaps, SortedMap / TreeMap can help you. Otherwise, a
(Array-/Linked)List might be what you are looking for.

Ciao,
Ingo
 
S

Sridhar

I guess you are right... I made the blunder of assuming that the order
of the elements will be maintained. Will surely try out the other
alternatives. Thanx everyone
 
J

Joan

Sridhar said:
Consider the following snippet to display the contemts of a HashMap in
a sequential manner.

//temp2 is a hashmap
Set set2=temp2.entrySet();
Iterator iHash2=set2.iterator();

while(iHash2.hasNext()){
Map.Entry me2= (Map.Entry) iHash2.next();
System.out.println(me2.getKey());
}

I printed the order in which the elements were entered in the HashMap
and later printed the hashMap using the above algorithm... both are
different.... Any idea why??

I'm just printing the keys here. During insertion the order followed
for the key is
r1,s3,s2,s1

but when i print the hashmap the order is:
s2,s3,r1,s1
Use TreeMap instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,173
Latest member
GeraldReund
Top