Java 枚举方法 - 返回相反方向的枚举 [英] Java Enum Methods - return opposite direction enum

查看:27
本文介绍了Java 枚举方法 - 返回相反方向的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个枚举方向,它有一个返回相反方向的方法(以下在语法上不正确,即无法实例化枚举,但它说明了我的观点).这在 Java 中可行吗?

I would like to declare an enum Direction, that has a method that returns the opposite direction (the following is not syntactically correct, i.e, enums cannot be instantiated, but it illustrates my point). Is this possible in Java?

代码如下:

public enum Direction {

     NORTH(1),
     SOUTH(-1),
     EAST(-2),
     WEST(2);

     Direction(int code){
          this.code=code;
     }
     protected int code;
     public int getCode() {
           return this.code;
     }
     static Direction getOppositeDirection(Direction d){
           return new Direction(d.getCode() * -1);
     }
}

推荐答案

对于那些被标题吸引到这里的人:是的,您可以在枚举中定义自己的方法.如果您想知道如何调用这样的非静态方法,您可以按照与任何其他非静态方法相同的方式进行调用 - 在定义或继承该方法的类型实例上调用它.在枚举的情况下,此类实例只是 ENUM_CONSTANT s.

For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

所以你只需要EnumType.ENUM_CONSTANT.methodName(arguments).

现在让我们从问题回到问题.解决方案之一可能是

Now lets go back to problem from question. One of solutions could be

public enum Direction {

    NORTH, SOUTH, EAST, WEST;

    private Direction opposite;

    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }

    public Direction getOppositeDirection() {
        return opposite;
    }

}

现在 Direction.NORTH.getOppositeDirection() 将返回 Direction.SOUTH.

这里有一些更hacky"的方式来说明@jedwards评论但它感觉不如第一种方法灵活,因为添加更多字段或更改它们的顺序会破坏我们的代码.

Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}

这篇关于Java 枚举方法 - 返回相反方向的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆