[英]java enums but like public static final int?
I want to have a list of constants like A, B, C related to integers 1, 2, 3 我想要一个与整数1,2,3相关的常量列表,如A,B,C
I know you can do like 我知道你可以这样做
class Example {
public static final int A = 1;
etc...
}
and 和
enum Example {
A(1), ... etc;
some initialization of an integer
}
But is there a way to do it like the public static final but as succinct as enums? 但有没有办法像公共静态决赛那样做,但像枚举一样简洁? When I use A and I really mean 1 I don't want to call Example.A.value or something like that. 当我使用A时,我的意思是1我不想调用Example.A.value或类似的东西。
One way would be to use an interface, where variables are public, static and final by default: 一种方法是使用接口,默认情况下变量是public,static和final:
interface Example {
int A = 1;
int B = 2;
}
If I understand what you're asking correctly, you want to do something like this: 如果我理解你正确的要求,你想做这样的事情:
enum Example {
A = 1,
B = 2,
....
}
There is no nice simple syntax for this. 这没有简单的语法。
You either have to write out some constants: 你要么必须写出一些常量:
public interface Example {
public static final int A = 1;
public static final int B = 2;
....
}
...Or you can add some other value
to the enum: ...或者您可以为枚举添加一些其他value
:
public enum Example {
A(1),
B(2)
....
private final int val;
public Example (int val) {
this.val = val;
}
public int getValue() {
return val;
}
}
我认为最短的解决方案是:
public static final int A = 1, B = 2, C = 3;
If you really want to use Enum, then you can override toString() method in your enum, to get the value printed when you print your Enum Instance: - 如果你真的想使用Enum,那么你可以覆盖枚举中的toString()方法,以便在打印枚举实例时获得打印值: -
enum Example {
A(1), B(2);
private int val;
private Example(int val) {
this.val = val;
}
@Override
public String toString() {
switch (this) {
case A:
return String.valueOf(val);
case B:
return String.valueOf(val);
}
return super.toString();
}
}
public class D {
public static void main(String[] args) {
Example a = Example.A;
Example b = Example.B;
System.out.println(a); // Prints 1
System.out.println(b); // Prints 2
}
}
Ideally your above enum is just like the below class: - 理想情况下,您的上述枚举就像下面的类: -
class Example {
public static final int A = 1;
public static final int B = 2;
}
So, I don't see the necessity of using Enums.. 所以,我没有看到使用Enums的必要性..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.