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

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

问题描述

我想声明一个枚举Direction,它具有一个返回相反方向的方法(以下语法不正确,即,不能实例化枚举,但它说明了我的观点).用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天全站免登陆