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() );
}
}
}
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);
}
您可以将HashSet
更改为Arraylist
,这是列表的常见类型。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.