Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this block of code behave differently..?

 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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.
 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ulf,

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



Thanks
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 1277
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic