thisisdude
thisisdude

Reputation: 576

How to declare integer values as constants using enum class?

I have a set of integer values which I need to define as a part of enum, I'm doing this.

public enum Test{

    763("763"),
    1711("1711"),
    8050("8050"),
    9311("9311");

    private Integer test;

    Test(Integer test) {
        this.test= test;
    }

    public Integer getTest() {
        return test;
    }

}

It gives me unexpected token on the first line.. What is missing here?

Thanks in advance.

Upvotes: 0

Views: 146

Answers (2)

rieckpil
rieckpil

Reputation: 12021

Java does not allow variables to start with a number. Take a look at the official variable rules. Furthermore, you should pass test as an integer and not as a String.

A working solution might look like the following:

public enum Test {
  T_763(763),
  T_1711(1711),
  T_8050(8050),
  T_9311(9311);

  private Integer test;

  Test(Integer test) {
    this.test = test;
  }

  public Integer getTest() {
    return test;
  }

}

Upvotes: 3

Mark Bramnik
Mark Bramnik

Reputation: 42481

  1. Typo with opening curly brace in constructor
  2. Enumerations themselves can't be numbers (these are names that can't be numbers in java)
  3. The value is declared integer but you pass String.

Here is a fixed version of what you're trying to do:

public enum Test {
    T_763(763),
    T_1711(1711),
    T_8050(8050),
    T_9311(9311);

    private final Integer test;
    Test(Integer test) {
        this.test= test;
    };
    public Integer getTest() {
        return test;
    }

}

Upvotes: 1

Related Questions