开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜