开发者

last element of the array gets printed first on iteration

开发者 https://www.devze.com 2023-04-03 06:15 出处:网络
import java.util.*; class next { public static void main( String args[] ) { String elements[] = { \"Suhail\" , \"S开发者_JAVA百科hadow\" , \"Stars\" };
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

精彩评论

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

关注公众号