aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet question 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 "HashSet question" Watch "HashSet question" New topic
Author

HashSet question

vinita Kh
Ranch Hand

Joined: Feb 19, 2002
Posts: 49
when i tried to run this code it prints "abcdef"
nebody plz explain y?
output of the following program?
import java.util.*;
class Question {
public static void main(String[] args) {
HashSet set = new HashSet();
String s1 = "abc";
String s2 = "def";
String s3 = "";
set.add(s1);
set.add(s2);
set.add(s1);
set.add(s2);
Iterator i = set.iterator();
while(i.hasNext()) {
s3 += (String)i.next();
}
System.out.println(s3);
}
}
A)abcdefabcdef
B)defabcdefabc
C)fedcbafedcba
D)defabc
w
Tim Murphy
Greenhorn

Joined: Apr 11, 2002
Posts: 18
Hashing uses the String, in this example "abc" and "def" as unqiue identifies. When a String comes along that is the same as a previously added String, it replaces the old String. Therefore in your HashSet you add the two objects, then you replace them with the same objects again.
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5371
Hashset implements Set interface.
and Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
HTH


"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
Tim Murphy
Greenhorn

Joined: Apr 11, 2002
Posts: 18
also Vinita, the output is defabc, which seems to mean it is 'First In Last Out'
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5371
you can not be sure of the order ...
Jackie Wang
Ranch Hand

Joined: Apr 18, 2002
Posts: 315
What's the pro and cons for the data structure of
1) hashset(as I know it only have key but not value), and linked list.
2) HashMap and Hashtable.
Anyone can help me? thanks!
Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
Hashtable does not allow null values to be stored, whereas Hashmap does.
Clement


best regards,<br />Steven<br />SCJP, SCEA
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
Why would you use a HashSet with no value?
I ran some performance tests between a LinkedList and an ArrayList and I could not find any circumstance where a LinkedList performed better than an ArrayList. And I found plenty of circumstances where the LinkedList performed significantly worse than an ArrayList.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet question