public enum Planet {
MERCURY(false),
VENUS(false),
EARTH(false),
MARS(false),
JUPITER(false),
SATURN(false),
URANUS(false),
NEPTUNE(false);
}
public boolean isCurrent;
Planet(boolean isCurrent){
this.isCurrent = isCurrent;
}
public static void next(){
if(planet == VENUS){
VENUS.isCurrent = false;
EARTH.isCurrent = true;
MARS.isCurrent = false;
JUPITER.isCurrent = false;
SATURN.isCurrent = false;
URANUS.isCurrent = false;
NEPTUNE.isCurrent = false;
}
if(planet == EARTH){
VENUS.isCurrent = false;
EARTH.isCurrent = false;
MARS.isCurrent = true;
JUPITER.isCurrent = false;
SATURN.isCurrent = false;
URANUS.isCurrent = false;
NEPTUNE.isCurrent = false;
}
...
}
我找到了这个解决方案,
private enum Planet { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
public Planet getNext() {
return this.ordinal() < Planet.values().length - 1
? Planet.values()[this.ordinal() + 1]
: null;
}
}
但我无法使用this,因为这个枚举在其他类中作为静态导入;
现在我使用以下结构:
public static Planet setNewCurrent(){
for(Planet planet : Planet.values()){
if(planet == VENUS){
VENUS.isCurrent = false;
EARTH.isCurrent = true;
MARS.isCurrent = false;
JUPITER.isCurrent = false;
SATURN.isCurrent = false;
URANUS.isCurrent = false;
NEPTUNE.isCurrent = false;
}
if(planet == EARTH){
VENUS.isCurrent = false;
EARTH.isCurrent = false;
MARS.isCurrent = true;
JUPITER.isCurrent = false;
SATURN.isCurrent = false;
URANUS.isCurrent = false;
NEPTUNE.isCurrent = false;
}
...
}
}
有谁知道像这样获取NextPlanet()的一些方便的方法
planet.getNext().isCurrent = true;
最佳答案
我希望您确实意识到您可以拥有如下内容:
public enum Planet {
MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
public Planet getNext() {
return this.ordinal() < Planet.values().length - 1
? Planet.values()[this.ordinal() + 1]
: null;
}
}
private Planet planet;
public void someFunction()
{
planet = Planet.MARS;
planet = planet.getNext();
if(planet != null)
{
doStuff();
}
}
当然,您可以根据在字段变量中选择的任何一个,将 switch-case 语句与枚举一起使用:Java using enum with switch statement
根本不需要一个 boolean 变量来确定哪个是“当前选中的”。
编辑:根据您的评论,您需要 Planet 的单例实例。幸运的是,您可以为此使用枚举本身:
public enum Planet {
MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE;
private static Planet currentPlanet = MERCURY;
public static Planet getCurrentPlanet()
{
return currentPlanet;
}
public static boolean setToNext() {
boolean retVal = this.ordinal() < Planet.values().length - 1;
currentPlanet = this.ordinal() < Planet.values().length - 1
? Planet.values()[this.ordinal() + 1]
: Planet.values()[0];
return retVal; //returns false when it was the last element of the enum
}
}
public void doSomething()
{
Planet planet;
do
{
planet = Planet.getCurrentPlanet();
//do things with planet, like write out their names
System.out.println(planet.name());
}
while(Planet.setToNext());
}
关于java - 如何在静态枚举中获取下一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25323916/