How to access a specific member in Java enum by Index value?
我想打印第二个索引值,即SUMMER。
1 2 3 4 5 6 7 8 9 |
如何实现呢?
您的代码几乎可以正常工作。仔细查看
它不是接受参数的方法,它会返回整个数组。因此,您需要在方法作为array-access之后转移访问权限:
1 | Season.values()[2] |
您应该避免按索引访问
1 2 3 4 5 6 | public enum Season { FALL, // 3 -> 0 SPRING, // 1 -> 1 SUMMER, // 2 -> 2 WINTER // 0 -> 3 } |
或稍后在您的枚举中添加一些值而又不记得依赖于订单的代码,那么您将破坏代码。相反,您可以设置
1 2 3 4 5 | Map<Integer, Season> indexToSeason = new HashMap<>(); indexToSeason.put(0, Season.WINTER); indexToSeason.put(1, Season.SPRING); indexToSeason.put(2, Season.SUMMER); indexToSeason.put(3, Season.FALL); |
然后使用该地图进行访问:
1 2 3 | public Season getSeasonByIndex(int index) { return indexToSeason.get(index); } |
如果要获取特定索引的枚举,请尝试:
1 | Season.values()[index] |
您可以通过键入所需的值来访问它们,例如
如果在类枚举中搜索
如果实际上需要通过索引值访问Enum,请使用
在这里找到有关枚举的更多信息。
System.out.println(Season.values()[2]);