枚举构造函数中的 Java 字节类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17634140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java byte type in enum constructor
提问by varuog
public enum Rank {
TEN("Ten",1),
NINE("Nine",2),
EIGHT("Eight",0),
SEVEN("Seven",0);
private final String name;
private final int point;
/*
* @param rank should be byte
*/
private Rank(String name,int point)
{
this.name=name;
this.point=point;
}
How to replace int to byte in point. One way i can think of is using TEN("Ten",Byte.parseByte("1"));
如何将 int 替换为字节点。我能想到的一种方法是使用TEN("Ten",Byte.parseByte("1"));
Is there any better or/and shorter approach?
有没有更好或/和更短的方法?
回答by Jashaszun
Just cast
to a byte
, like so:
只是cast
到 a byte
,像这样:
public enum Rank {
TEN("Ten", (byte)1),
NINE("Nine", (byte)2),
EIGHT("Eight", (byte)0),
SEVEN("Seven", (byte)0);
private final String name;
private final byte point;
private Rank(String name, byte point)
{
this.name = name;
this.point = point;
}
回答by Joni
A shorter approach is casting.
更短的方法是铸造。
TEN("Ten", (byte) 1));
回答by kan
Just a style suggestion, move the cast in the constructor, so it looks cleaner:
只是一个样式建议,在构造函数中移动强制转换,这样看起来更干净:
public enum Rank {
TEN("Ten", 1),
NINE("Nine", 2),
EIGHT("Eight", 0),
SEVEN("Seven", 0);
private final String name;
private final byte point;
private Rank(String name, int point)
{
this.name = name;
this.point = (byte)point;
}