列表元素的顺序

3

Consider the following enum:

public enum Type{
     INTEGER,
     DOUBLE,
     BOOLEAN
}

现在,我有以下这行代码:

List<Type> types = Arrays.asList(Type.values());

这个列表中的元素是否按照枚举时的顺序排列?这个顺序可靠吗?

3个回答

4

是的。Java枚举类型规范指出:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

它将返回一个包含常量声明的数组。关于 Arrays.asList() 方法,您也可以依赖其顺序:

返回由指定数组支持的固定大小列表。(对返回的列表所做的更改“写入”到数组中。)

请考虑下面的示例,这是初始化 List 的一种非常常见的方式:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

列表的顺序将与数组中的顺序相同。

所以,是的,很明显数组的顺序将与枚举的顺序一致。但是Arrays.asList()方法呢?该方法是否指定不更改顺序? - user3663882
所以,我发现Arrays.asList返回的列表顺序是不可靠的。文档 我猜,如果我们需要可靠的顺序,我们就必须自己构建一个列表... - user3663882
asList() 的顺序是可预测的,我在我的回答中已经澄清了这一点。 - Magnilex

2

0
如果您想要保持元素的顺序,请使用LinkedList:-

List<Type> types = new LinkedList<Type>(Arrays.asList(Type.values()));


我需要保持与它们在枚举中放置的相同顺序。 - user3663882
我指的是可靠的顺序。 - user3663882
是的,LinkedList会维护顺序,但是你所说的“可靠”是什么意思? - AnkeyNigam
虽然 LinkedList 是有序的,但是任何 List 都是有序的。这将保持顺序,但为什么要先创建一个 List,然后再创建一个 LinkedList 呢? - Magnilex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接