实例化枚举类 [英] Instantiate enum class

查看:151
本文介绍了实例化枚举类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我有以下枚举类,

  public enum Sample {
READ,
WRITE
}

在下面的类中,我试图测试枚举类, / p>

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

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

这里我指定示例.READ 然后将其作为参数传递给方法 testEnumSample
如果我们要实例化枚举类并将其作为参数传递给我们需要做什么?

解决方案


这里我需要指定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.

这篇关于实例化枚举类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆