有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

我可以遍历的java常量集

我经常遇到这样一种情况,我需要定义一组常量,然后循环遍历它们。比如说卡片套装,我需要向用户显示可用套装的列表

我看到的两个选项是enum或static int。但问题是,当我需要遍历列表时,我最终使用带有value()和Ordinal()的enum。很多人说使用这些是不好的,你应该回到static int

你们如何在需要迭代的地方编写一组常量?最佳做法是什么

谢谢


共 (1) 个答案

  1. # 1 楼答案

    可以使用values()方法。事实上Java tutorial for enums明确提到了这一点:

    The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

    for (Planet p : Planet.values()) {
        System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
    }
    

    与常量int相比,枚举提供了一些优势,例如更强的类型检查。但是,如果您必须进行代码调优,并且确定没有过早地进行优化,那么可以使用常量int和包含它们的数组<免责声明:我不推荐这种做法。默认情况下,请不要这样做

    private static final int SUIT_SPADES = 1;
    private static final int SUIT_CLUBS = 2;
    private static final int SUIT_HEARTS = 4;
    private static final int SUIT_DIAMONDS = 8;
    
    private static final int[] SUITS = new int[] { 
       SUIT_SPADES, SUIT_CLUBS, SUIT_HEARTS, SUIT_DIAMONDS };
    
    ...
    for ( int suit : SUITS ) { ... }