• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

iterator() mtd

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hai Ranchers,
Sorry for posting a lot of questions. Please have a look at the following code.
import java.util.*;
public class Question1 {
public static void main(String args[]){
HashSet s=new HashSet();
String s1="abc",s2="def",s3= " ";
s.add(s1);
s.add(s2);
s.add(s1);
s.add(s2);
Iterator i=s.iterator();
while(i.hasNext()){
s3 += (String)i.next();
}
System.out.println(s3);
}
}

The final value of the String s3 is "defabc" . I thought it should be "abcdef". I don't know how it is reversed.Can anyone clear my doubt.

Thanks
sudha
 
Ranch Hand
Posts: 1246
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried the code on my machine. The output is abcdef.
I am on win2k and java 1.3
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sudha
On my machine I get the output " defabc" - note the blank space is also in there from the initialization.
BUT, a HashSet is a non-ordered set and so it is not surprising that different systems give different outputs. If you change the set from a HashSet to a TreeSet (which is an ordered set) then you will get the output that you were expecting.
I'm sure that there is more to be said about this but I hope the above helps
All the best
Simon
 
Ranch Hand
Posts: 782
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I compiled & run code first in my mind & then on my machine.I got "abcdef" .When i was doing from my mind,i thought that Set always contains unique elements, and therefore no use of line 3 & line 4.Since s1 & s are already added at Line 1 7 Line 2 respectively(remebering that v r adding is Set...unique)
Bye.
Viki.
------------------
Count the flowers of ur garden,NOT the leafs which falls away!
 
If you want to look young and thin, hang around old, fat people. Or this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic