-1

I have an enum with a constructor:

enum myEnum {
    A(0), B(1), C(2);

    private final short value;

    private myEnum(short value) {
        this.value = value;
    }

    public short getValue() {
        return this.value;
    }
}

Unfortunately, Eclipse is letting me know that there is no constructor accepting a single int. Therefore I am relegated to casting to a short...

A((short) 0), B((short) 1), C((short) 2);

...whether this is done for each value or taking an int in the constructor and casting at assignment.

Is there a better way to do this than taking the time to cast, or is there no better solution?

JavaA
  • 37
  • 11
  • java whole number literals (`1`, `-234`, etc.) are always `int`s, so there is no way around casting – Lino Jul 18 '18 at 13:40
  • There is no literals for short values. You have to cast. – Murat Karagöz Jul 18 '18 at 13:42
  • Why not just make a second constructor to take ints instead of shorts? ```private myEnum(int value) { this.value = (short) value; }``` – Green Cloak Guy Jul 18 '18 at 13:43
  • why are you using shorts in the first place? – Lino Jul 18 '18 at 13:45
  • @Lino That's the answer I was afraid of, and what turned out to be the duplicate I just accepted. Thanks. (I'm using a `short` because of other pre-existing methods in the project.) – JavaA Jul 18 '18 at 14:10

2 Answers2

0

You can use

short shortValue = Integer.valueOf(0).shortValue();

Under the hood it's still the same. So it's kind to turn a blind eye on.

LuCio
  • 5,055
  • 2
  • 18
  • 34
-1

You always have to cast, because unfortunately there is no literal format for shorts, what I suggest is to add another constructor to your enum:

private myEnum(int value) {
    this((short) value);
}

This way you will avoid casting it for the values of the enum.

Mustapha Belmokhtar
  • 1,231
  • 8
  • 21