File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashset Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashset" Watch "hashset" New topic
Author

hashset

weiliu lili
Ranch Hand

Joined: Apr 11, 2002
Posts: 46
import java.util.*;
public class Test {

public static void main(String[] args){
Integer a = new Integer(4);
Integer b = new Integer(8);
Integer c = new Integer(4);
HashSet hs = new HashSet();
hs.add(a);

hs.add(c);
hs.add(b);
System.out.println(hs);
}
}
the running result of it is[8,4] why not [4,8]? how can I enforce the result as [4,8]?
thanks
Asif Mahmood
Greenhorn

Joined: Jun 11, 2001
Posts: 29
Weiliu, you're getting unexpected result because hash set does not guarantee the order of its elements because it's based on hashing. If you want to enforce the results, you can use TreeSet.
Best regards,
-Asif
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashset
 
Similar Threads
Q on collections framework: iteration order
Why this block of code behave differently..?
Question on HashSet & LinkedHashSet
A simple Hash Map Example.
HashSet problem