【问题标题】:What is the order of elements when we iterate using for-each construct in collections?当我们在集合中使用 for-each 结构进行迭代时,元素的顺序是什么?
【发布时间】:2018-11-16 09:10:09
【问题描述】:

当我们使用for each 构造迭代集合时,java 在每次迭代时从集合中挑选每个元素的逻辑是什么,是随机的还是某种定义的排序?还是与自然排序有关?

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

【问题讨论】:

  • 真的取决于收藏。如果它是list,那么它就是插入顺序。 students是什么类型的收藏?
  • 这个循环使用集合的 Iterable 特性,它使用它的底层 Iterator ,所以这完全取决于给定集合的迭代器是如何实现的。例如Listdocs.oracle.com/javase/8/docs/api/java/util/…

标签: java collections foreach


【解决方案1】:

假设你的意思

for (Student student:students)

迭代顺序由Iterablestudents 类型的实现决定(除非students 是一个数组,在这种情况下顺序是明确定义的)。

例子:

对于Lists,顺序是明确定义的。

对于一般的Sets 它不是(尽管一些Sets,如TreeSet 确实有顺序)。

或者是与自然排序相关的

有时是这样。如果您正在迭代元素类型实现ComparableTreeSet,则顺序将是元素类型的自然顺序(假设您没有将定义不同顺序的Comparator 传递给TreeSet构造函数)。

【讨论】:

    【解决方案2】:

    这取决于您使用的集合类型

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

    等价于

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

    i.next() 获取下一个学生对象,其(next() 方法)实现基于集合类型。

    它可能与内存中的顺序相同。

    阅读更多:https://javarevisited.blogspot.com/2016/02/how-does-enhanced-for-loop-works-in-java.html#ixzz5X0Wf0Eak

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2019-01-12
      • 1970-01-01
      • 2011-02-16
      相关资源
      最近更新 更多