java - 列表元素的顺序

标签 java enums

考虑以下枚举:

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/

相关文章:

java - 颜色代码枚举

java - 在代码部署期间实现零停机时间

Javamail,获取邮件正文

java - 如何处理多部分异常

java - 从 Class<? 中获取枚举实例使用字符串值扩展枚举>?

angular - 带有值和显示名称的 typescript 枚举

java - 了解实体映射到数据库 View 的删除或更新

java - 如何使 JFrame 不可显示?

c# - 可空枚举不会触发 C# 中有效枚举值列表的智能感知

java - 数组作为 switch 语句的选项