0

Is it possible to define array in this way in JAVA, otherwise are there an alternative close this definition?

private final int CONST_0= 0;
private final int CONST_1= 1;
private final int CONST_2= 2;
private final int CONST_3= 3;
private final String[] CONST_TXTRECORDS = new String[] 
                                          {[CONST_0] = "test0",
                                          {[CONST_1] = "test1",
                                          {[CONST_2] = "test2",
                                          {[CONST_3] = "test3"};
1
  • 1
    this is not syntactically correct. I suggest that you use enum instead. Commented Sep 7, 2012 at 9:21

3 Answers 3

4

Perhaps you should look at enums.

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

You can use enums as map keys, using either the generic Map classes or the specialized EnumMap which I guess is a bit more efficient.

https://docs.oracle.com/javase/8/docs/api/java/util/EnumMap.html

Sign up to request clarification or add additional context in comments.

5 Comments

You're right, I just pasted the first thing google threw at me.
Google often picks Javadocs from 1.4.2 and 1.5.0. Java 6 will be EOL in a couple of months. ;)
@PeterLawrey you're right of course, but I haven't yet worked with any client in the real world that used Java 7 (which I guess is the reason that I still link to 6)
@SeanPatrickFloyd You are right but I think when people look at your answers in years to come, they might be using Java 7 (and it looks nicer ;)
@PeterLawrey yeah, perhaps I'll start doing that
3

What you are trying to define is not an array, but an associative array, or in Java speak, a Map.

You probably want to use a HashMap (or, as the others wrote, an enum, depending on how static your requirements are).

See: Java Tutorial > Collections Trail > The Map Interface

Comments

2
public enum MyNum {
    CONST_0(new int[]{0},"test0"),
    CONST_1(new int[]{1},"test1"),
    CONST_2(new int[]{2},"test2"),
    CONST_3(new int[]{3},"test3");

    private String value;
    private int key[] ;

    MyNum(int key[],String value){
        this.value = value;
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public int[] getKey() {
        return key;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.