aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes LinkedHashSet and LinkedHashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "LinkedHashSet and LinkedHashMap" Watch "LinkedHashSet and LinkedHashMap" New topic
Author

LinkedHashSet and LinkedHashMap

Sharmila Punde
Ranch Hand

Joined: Dec 26, 2007
Posts: 133
Hi All,
Can someone please explain following -


Prints [1, 2, 4, 3] [1243] [1234] . Because PriorityQueue does not reflect ordering in iterator and toString. Ordering is reflected only by peek,poll,remove methods.

My question is , do the LinkedHashSet and LinkedHashMap reflect ordering in toString() method?

Regards


Regards, Sharmila.
We will have a future if we save Nature!
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

LinkedHashSet and LinkedHashMap both are ordered collections (they maintain insertion order). So their iterators iterate over their elements in insertion order. Both of these classes inherit the toString method from AbstractCollection class. The documentation of the toString method in AbstractCollection class says
The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]").

So the toString method for both of them will reflect the ordering...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Sharmila Punde
Ranch Hand

Joined: Dec 26, 2007
Posts: 133
Thanks Ankit,
It is very neat and nice explaination.
Thank you very much again.
Regards
Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 255

Hey Sharmila,

Prints [1, 2, 4, 3] [1243] [1234] . Because PriorityQueue does not reflect ordering in iterator and toString. Ordering is reflected only by peek,poll,remove methods.


PriorityQueue reflects the natural ordering or by the order mentioned by given comparator in its functions, iterator and toString method. As even your code is mentioning the same. you just put not by mistake in the above quote.


Regards
Salil Verma
Arunava Sircar
Greenhorn

Joined: Sep 13, 2009
Posts: 4
Hi Salil,

I think what you have mentioned is wrong and what Sharmila has written is correct. PriorityQueue will never reflect the order if the elements are printed using the iterator or toString. The order is determined by natural ordering or by a Comparator and can be seen by the peek(), poll(), remove() methods.

--
Arunava
 
Don't get me started about those stupid light bulbs.
 
subject: LinkedHashSet and LinkedHashMap