Reputation: 2436
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
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.
Upvotes: 2
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 List
s, the order is well defined.
For general Set
s it is not (though some Set
s 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