从 Arrays.asList 返回的列表是否与原始数组集合保持相同的顺序? [英] Does the list returned from Arrays.asList maintain the same order as the original array collection?

查看:19
本文介绍了从 Arrays.asList 返回的列表是否与原始数组集合保持相同的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList,我要对其进行多次迭代,但它似乎没有保持迭代顺序.我看得更深入,似乎(由其他人)为此迭代编写的自定义迭代器标记首先采用传入的 ArrayList 并在迭代之前使用 Arrays.asList 将其桥接到 Object[] 集合.迭代顺序是否丢失?Arrays.asList 是这样吗?

I've got an ArrayList that I'm iterating over several times, and it looks like it isn't maintaining the order of iteration. I looked deeper, and it appears that the custom iterator tag that was written for this iteration (by someone else) is first taking the passed in ArrayList and using Arrays.asList to bridge it to an Object[] collection before iterating. Is the order of iteration being lost? Is that expected with Arrays.asList?

以下是操作对传递给迭代器标签的原始集合所做的操作:

Here is the what the operation does with the original collection passed into the iterator tag:

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 仍然由原始数组支持,因此项目应该按照它们在数组中的顺序出现.

The List is still backed by the original array, so items should appear in the same order as they do in the array.

另外,注意 asList 是一个泛型方法,所以 Arrays.asList(T[]) 将返回一个 List.

Also, note that asList is a generic method, so Arrays.asList(T[]) will return a List<T>.

至于另一个方向,ListtoArray

返回一个包含所有此列表中的元素正确序列(从第一个元素到最后一个元素).

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

有两个 toArray 方法.第一个返回一个 Object[],第二个将一个数组作为它的参数并作为相同类型的数组返回.

There are two toArray methods. The first returns an Object[], the second take an array as its argument and returns as array of the same type.

这样的事情并不少见,以String数组为例:

Something like this is not uncommon, using an array of String as an example:

String[] y = x.toArray(new String[0]);

(此示例取自 JavaDoc for List)

(This example is taken from the JavaDoc for List<E>)

这篇关于从 Arrays.asList 返回的列表是否与原始数组集合保持相同的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆