且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实例化枚举类

更新时间:2023-02-19 21:31:54


这里我需要指定Sample.READ作为参数传递。相反,如果我们要实例化枚举类并将其作为参数传递给我们需要做的事情?


什么将实例化枚举类甚至意味着?枚举的一点是,有一个固定的值集合 - 您不能再创建更多。如果你想这样做,你不应该使用一个枚举。



还有其他方法可以获取枚举值。例如,您可以获得第一个声明的值:

  testEnumSample(Sample.values()[0]); 

或者传入名称并使用 Sample.valueOf

  testEnumSample(READ); 

...

样本sample = Sample.valueOf(sampleName);

如果您解释了您尝试实现的内容,那么可以帮助您更容易。 p>

Consider I am having the following enum class,

public enum Sample {
    READ,
    WRITE
}

and in the following class I am trying to test the enum class,

public class SampleTest {
    public static void main(String[] args) {
        testEnumSample(Sample.READ);
    }

    public static void testEnumSample(Sample sample) {
        System.out.println(sample);
    }
}

Here I am specifying Sample.READ then passing it as the parameter to the method testEnumSample. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

Here I need to specifying Sample.READ to pass it as parameter. Instead if we want to instantiate the enum class and pass it as parameter what we need to do?

What would "instantiate the enum class" even mean? The point of an enum is that there are a fixed set of values - you can't create more later. If you want to do so, you shouldn't be using an enum.

There are other ways of getting enum values though. For example, you could get the first-declared value:

testEnumSample(Sample.values()[0]);

or perhaps pass in the name and use Sample.valueOf:

testEnumSample("READ");

...

Sample sample = Sample.valueOf(sampleName);

If you explained what you were trying to achieve, it would make it easier to help you.