是否有更好,更有效的方法:
我正在输入2个值然后在列表中检查它们,就好像current = 3然后它返回true以检查一个,两个和三个
注意:这些值(一,二,三)只是我使用中的示例的占位符,除了它们具有不同的优先级之外,它们之间没有关系。
enum Foo {
ONE(1), TWO(2), THREE(3)
private final int priority;
public Foo(int priority) {this.priority = priority;}
public int getPriority() {return priority;}
}
public boolean checker(Foo current, Foo check) {
if (check == ONE) {
if (current == ONE || current == TWO
|| current == THREE) {
return true;
}
}
if (check == TWO) {
if (current == TWO || current == THREE) {
return true;
}
}
if (check == THREE) {
if (current == THREE) {
return true;
}
}
return false;
}
答案 0 :(得分:1)
我会用这种方式实现枚举:
enum Foo {
ONE(1), TWO(2), THREE(3);
private final int priority;
private Foo(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
public boolean check(Foo check) {
return this.getPriority() >= check.getPriority();
}
}
然后致电:
Foo current = Foo.THREE;
System.out.println(current.check(Foo.TWO));
这种方式更多是OOP。
答案 1 :(得分:0)
您似乎总是在检查current
是否等于或大于check
。如果是这样,那么你可以使用整数。如果需要命名它们,可以使用一些常量整数,例如public final static int ONE = 1;
。
public boolean checker(int current, int check) {
return current >= check;
}
如果您想限制特定数字,例如示例中的1,2,3,请先检查参数:
public boolean checker(int current, int check) {
int MIN = 1;
int MAX = 3;
if(current < MIN || current > MAX || check < MIN || check > MAX) {
return false;
}
return current >= check;
}
答案 2 :(得分:0)
话虽如此,以下内容的效率,清晰度和逻辑上与您发布的代码相同:
public boolean checker(Foo current, Foo check) {
switch (check) {
case THREE:
if (current == TWO)
return false;
case TWO:
if (current == ONE)
return false;
default:
return true;
}
}