考虑以下枚举:
public enum Type{
INTEGER,
DOUBLE,
BOOLEAN
}
现在,我有以下行:
List<Type> types = Arrays.asList(Type.values());
列表中包含的元素的顺序是否与它们放入枚举中的顺序相同?这个顺序靠谱吗?
最佳答案
是的。 Java Language Specification for Enums状态:
/**
* 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()
方法,您也可以依赖它的顺序:
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)
考虑下面的示例,这是初始化 List
的一种非常常见的方法:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
列表的顺序将与数组中的顺序相同。
关于java - 列表元素的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31178660/