Suhail Gupta
Suhail Gupta

Reputation: 23246

last element of the array gets printed first on iteration

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

Upvotes: 1

Views: 495

Answers (3)

user425367
user425367

Reputation:

You can change your HashSet to an Arraylist which is the common type for lists.

Upvotes: 0

Martin Gamulin
Martin Gamulin

Reputation: 3865

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);
}

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47373

HashSet doesn't guarantee any order. Use LinkedHashSet instead to preserve insertion order.

Upvotes: 6

Related Questions