我有一个要迭代多次的 ArrayList,看起来它没有保持迭代顺序。我看得更深,似乎为这次迭代(由其他人)编写的自定义迭代器标记首先采用传入的 ArrayList 并使用 Arrays.asList 在迭代之前将其桥接到 Object[] 集合。迭代顺序是否丢失?这是 Arrays.asList 所期望的吗?
编辑:
这是对传入迭代器标记的原始集合执行的操作:
if(collection.getClass().isArray()) {
iterator = Arrays.asList((Object[]) collection).iterator();
} else if(collection instanceof Collection) {
iterator = ((Collection) collection).iterator();
} else if(collection instanceof Iterator) {
iterator = (Iterator) collection;
} else if(collection instanceof Map) {
iterator = ((Map) collection).entrySet().iterator();
}
最佳答案
List 仍然由原始数组支持,因此项目的出现顺序应与它们在数组中的顺序相同。
另外,请注意 asList 是一个泛型方法,所以 Arrays.asList(T[])
将返回 List<T>
.
至于另一个方向,List
的 toArray
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
有两个 toArray 方法。第一个返回 Object[]
,第二个以数组作为参数并返回为相同类型的数组。
这样的事情并不少见,以字符串数组为例:
String[] y = x.toArray(new String[0]);
(这个例子取自JavaDoc for List<E>
)
关于java - 从 Arrays.asList 返回的列表是否保持与原始数组集合相同的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4972406/