last element of the array gets printed first on iteration
import java.util.*;
class next {
public static void main( String args[] ) {
String elements[] = { "Suhail" , "S开发者_JAVA百科hadow" , "Stars" };
Set s = new HashSet( Arrays.asList( elements ) );
Iterator i = s.iterator();
while( i.hasNext() ) {
System.out.println( i.next() );
}
}
}
The output that follows is :
Stars
Shadow
Suhail
Why do i get the last element printed first ? I expected the output to be suhail , shadow , stars
HashSet
doesn't guarantee any order. Use LinkedHashSet
instead to preserve insertion order.
Is there a reason for using HashSet, in this case ArrayList would be perfect?
Do you just need an iteration?
for (final String string : elements) {
System.out.println(string);
}
You can change your HashSet
to an Arraylist
which is the common type for lists.
精彩评论