2011-09-08 31 views
1
import java.util.*; 
class next { 
public static void main(String args[]) { 
String elements[] = { "Suhail" , "Shadow" , "Stars" }; 
Set s = new HashSet(Arrays.asList(elements)); 
Iterator i = s.iterator(); 
    while(i.hasNext()) { 
System.out.println(i.next()); 
    } 
} 
} 

下面是輸出:最後一個元素最先被印在迭代

Stars 
Shadow 
Suhail 

爲什麼我得到第一個打印的最後一個元素?我預計輸出爲suhail , shadow , stars

回答

6

HashSet保證任何順序。改爲使用LinkedHashSet來保留廣告訂單。

0

是否有使用HashSet的原因,在這種情況下ArrayList會是完美的?

你只需要一個迭代?

for (final String string : elements) { 
    System.out.println(string); 
} 
0

你可以改變你的HashSetArraylist這是列出了常見的類型。

相關問題