Consider the following enum:
public enum Type{
INTEGER,
DOUBLE,
BOOLEAN
}
现在,我有以下这行代码:
List<Type> types = Arrays.asList(Type.values());
这个列表中的元素是否按照枚举时的顺序排列?这个顺序可靠吗?
是的。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");
values()
"返回按声明顺序排列的此枚举类型的常量数组。"(http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9)。因此,只要枚举类型不改变,您可以假设顺序将保持不变。LinkedList
:-
List<Type> types = new LinkedList<Type>(Arrays.asList(Type.values()));
LinkedList
会维护顺序,但是你所说的“可靠”是什么意思? - AnkeyNigamLinkedList
是有序的,但是任何 List
都是有序的。这将保持顺序,但为什么要先创建一个 List
,然后再创建一个 LinkedList
呢? - Magnilex
Arrays.asList()
方法呢?该方法是否指定不更改顺序? - user3663882asList()
的顺序是可预测的,我在我的回答中已经澄清了这一点。 - Magnilex