File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet question

 
vinita Kh
Ranch Hand
Posts: 49
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5382
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Tim Murphy
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
also Vinita, the output is defabc, which seems to mean it is 'First In Last Out'
 
R K Singh
Ranch Hand
Posts: 5382
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can not be sure of the order ...
 
Jackie Wang
Ranch Hand
Posts: 315
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 295
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashtable does not allow null values to be stored, whereas Hashmap does.
Clement
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic