Java枚举链接到另一个枚举 [英] Java Enum linking to another Enum
本文介绍了Java枚举链接到另一个枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望Java中的枚举器具有其他枚举作为属性。
I would like to have enumerator in Java having other enum as attribute.
public enum Direction {
Up(Down),
Down(Up),
Left(Right),
Right(Left);
private Direction opposite;
Direction(Direction opposite){
this.opposite = opposite;
}
}
所以我有不同的方向,对于每个我想要的知道相反。
对于Down和Right来说都可以正常工作,但是我无法初始化Up,因为Down未知(左相同的堡垒)。
So I have different Direction, and for each I want to know the opposite. It is working fine for Down and Right, but I can't initialize Up because Down is not known yet (same fort Left).
我怎么能初始化后编辑枚举变量吗?
How can I edit enum variables after initialisation ?
推荐答案
一种可能的解决方案-您可以将该登录名封装在方法中
One of the possible solution - you can encapsulate this login within the method
public Direction getOpposite() {
switch (this) {
case Up:
return Down;
case Down:
return Up;
case Left:
return Right;
case Right:
return Left;
}
return null;
}
使用该枚举的类的接口将是相同的
It will be the same interface for classes that will use this enum
这篇关于Java枚举链接到另一个枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文