我想创建一个名为increaseValue的方法,它的签名如下:
public Size increaseValue(Size s)
Run Code Online (Sandbox Code Playgroud)
我还有以下声明:
protected enum Size {XS, S, M, L, XL}
Run Code Online (Sandbox Code Playgroud)
我需要知道,如何在不使用Switch-Case语句的情况下使方法返回正确的值(即输入为L时的XL ......等)?
谢谢 !
你可以假设它们正在递增ordinal().我会添加一个方法Size.
protected enum Size {
XS, S, M, L, XL;
static final Size[] VALUES = values();
public Size incrementSize() { return VALUES[ordinal()+1]; }
public Size decrementSize() { return VALUES[ordinal()-1]; }
}
Run Code Online (Sandbox Code Playgroud)
注意:我不会认为XS是在XL之后,而是你得到一个错误(虽然不是很清楚)
注意:每次调用values()它都会创建一个新数组.它必须这样做,因为数组是可变的,你可能会改变它.我强烈建议您保存副本,避免values()每次都打电话.
您可以通过覆盖这些方法使错误消息更清晰.
protected enum Size {
XS {
public Size decrementSize() { throw new UnsupportedOperationException("No smaller size"); }
},
S,
M,
L,
XL {
public Size incrementSize() { throw new UnsupportedOperationException("No larger size"); }
};
static final Size[] VALUES = values();
public Size incrementSize() { return VALUES[ordinal()+1]; }
public Size decrementSize() { return VALUES[ordinal()-1]; }
}
Run Code Online (Sandbox Code Playgroud)