The Scientific Method
The Scientific Method

Reputation: 2436

What is the order of elements when we iterate using for-each construct in collections?

When we iterate collections using for each construct, what is the logic java uses to pick each element from the collection at each iteration, is that random or a some kind of defined sort? Or is that associated with natural ordering?

for(Student student:students){
  System.out.println(student);
}

Upvotes: 1

Views: 385

Answers (2)

suraj13k
suraj13k

Reputation: 416

It is based on what type of collection you are using

for(Student student:students){
 System.out.println(student.toString());
}

is equivalent to

for (Iterator<String> i = students.iterator(); i.hasNext();)
{ 
    Student student= i.next(); 
    System.out.println(student.toString()); 
}

i.next() gets the next student object and its(next() method) implementation is based on collection type.

It might be in the same order as in the memory.

Read more: https://javarevisited.blogspot.com/2016/02/how-does-enhanced-for-loop-works-in-java.html#ixzz5X0Wf0Eak

Upvotes: 2

Eran
Eran

Reputation: 393876

Assuming you meant

for (Student student:students)

the iteration order is determined by the Iterable's implementation of the type of students (unless students is an array, in which case the order is well defined).

Examples:

For Lists, the order is well defined.

For general Sets it is not (though some Sets such as TreeSet do have order).

or is that associated with natural ordering

Sometimes it is. If you are iterating over a TreeSet whose element type implements Comparable, the the order will be the natural ordering of the element type (assuming you didn't pass a Comparator defining different ordering to the TreeSet's constructor).

Upvotes: 3

Related Questions