permaculture playing cards*
The moose likes Java in General and the fly likes Why this block of code behave differently..? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why this block of code behave differently..?" Watch "Why this block of code behave differently..?" New topic
Author

Why this block of code behave differently..?

jami siva
Ranch Hand

Joined: Oct 16, 2009
Posts: 63

I read the statement for HashSet is , these are unordered and unsorted,
In first display method it displays elements in unordered way and in second one it display elements in ordered way,

What is the reason behind this.

Thanks in Advance
Sivva
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41511
    
  53
"unordered" just means that the order is not anything the programmer can rely on; it does not mean that the order will be random. For example, this kind of behavior could easily change from one JVM version to the next.


Ping & DNS - my free Android networking tools app
jami siva
Ranch Hand

Joined: Oct 16, 2009
Posts: 63
Hi Ulf,

I did not understand , can you give me more explanation please.



Thanks
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41511
    
  53
You misunderstand what the term "unordered" means in this context. It does not mean that the list is not ordered; in fact, the list is likely to be ordered in some deterministic way. What it means is that the programmer using the class can't rely on the ordering.

If you're interested in what the class does underneath the API, then Sun's JDK comes with the source code in a file named "src.zip"; in it you'll find HashSet.java file which you examine as to how it arrives at the ordering you observed. But be advised that the details can change from one JRE version to the next, because the javadocs explicitly say that this behavior is not guaranteed.

Note that sets don't have an ordering to begin with (at least HashSet does not) - they're not Lists.
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 928

as Ulf correctly stated, the elements are unordered,

since you cannot gaurantee the order of the list, they can be arranged in any way by the code logic.
Try the same example with a ArrayList class and check the output you get ....


My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why this block of code behave differently..?