Can I set enum start value in Java?

JavaEnums

Java Problem Overview


I use the enum to make a few constants:

enum ids {OPEN, CLOSE};

the OPEN value is zero, but I want it as 100. Is it possible?

Java Solutions


Solution 1 - Java

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See <http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html> for more.

Solution 2 - Java

Yes. You can pass the numerical values to the constructor for the enum, like so:

enum Ids {
  OPEN(100),
  CLOSE(200);

  private int value;    

  private Ids(int value) {
    this.value = value;
  }

  public int getValue() {
    return value;
  }
}

See the Sun Java Language Guide for more information.

Solution 3 - Java

whats about using this way:

public enum HL_COLORS{
		  YELLOW,
		  ORANGE;

		  public int getColorValue() {
			  switch (this) {
			case YELLOW:
				return 0xffffff00;
			case ORANGE:
				return 0xffffa500;    
			default://YELLOW
				return 0xffffff00;
			}
		  }
}

there is only one method ..

you can use static method and pass the Enum as parameter like:

public enum HL_COLORS{
		  YELLOW,
		  ORANGE;

		  public static int getColorValue(HL_COLORS hl) {
			  switch (hl) {
			case YELLOW:
				return 0xffffff00;
			case ORANGE:
				return 0xffffa500;    
			default://YELLOW
				return 0xffffff00;
			}
		  }

Note that these two ways use less memory and more process units .. I don't say this is the best way but its just another approach.

Solution 4 - Java

If you use very big enum types then, following can be useful;

public enum deneme {

    UPDATE, UPDATE_FAILED;

    private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>();
    private static final int START_VALUE = 100;
    private int value;

    static {
        for(int i=0;i<values().length;i++)
        {
            values()[i].value = START_VALUE + i;
            ss.put(values()[i].value, values()[i]);
        }
    }

    public static deneme fromInt(int i) {
        return ss.get(i);
    }

    public int value() {
    return value;
    }
}

Solution 5 - Java

If you want emulate enum of C/C++ (base num and nexts incrementals):

enum ids {
	OPEN, CLOSE;
	//
	private static final int BASE_ORDINAL = 100;
	public int getCode() {
		return ordinal() + BASE_ORDINAL;
	}
};

public class TestEnum {
	public static void main (String... args){
		for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
			System.out.println(i.toString() + " " + 
				i.ordinal() + " " + 
				i.getCode());
		}
	}
}

> OPEN 0 100 > CLOSE 1 101

Solution 6 - Java

The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.

Example:

public class TestEnum {
    enum ids {
        OPEN,
        CLOSE,
        OTHER;

        public final int value = 100 + ordinal();
    };

    public static void main(String arg[]) {
        System.out.println("OPEN:  " + ids.OPEN.value);
        System.out.println("CLOSE: " + ids.CLOSE.value);
        System.out.println("OTHER: " + ids.OTHER.value);
    }
};

Gives the output:

OPEN:  100
CLOSE: 101
OTHER: 102

Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.

Solution 7 - Java

@scottf

An enum is like a Singleton. The JVM creates the instance.

If you would create it by yourself with classes it could be look like that

public static class MyEnum {

    final public static MyEnum ONE;
    final public static MyEnum TWO;

    static {
        ONE = new MyEnum("1");
        TWO = new MyEnum("2");
    }

    final String enumValue;

    private MyEnum(String value){
        enumValue = value;    
    }

    @Override
    public String toString(){
        return enumValue;
    }


}

And could be used like that:

public class HelloWorld{

   public static class MyEnum {

       final public static MyEnum ONE;
       final public static MyEnum TWO;

       static {
          ONE = new MyEnum("1");
          TWO = new MyEnum("2");
       }

       final String enumValue;

       private MyEnum(String value){
           enumValue = value;    
       }

       @Override
       public String toString(){
           return enumValue;
       }


   }

    public static void main(String []args){
    
       System.out.println(MyEnum.ONE);
       System.out.println(MyEnum.TWO);
    
       System.out.println(MyEnum.ONE == MyEnum.ONE);
     
       System.out.println("Hello World");
    }
}

Solution 8 - Java

 public class MyClass {
    public static void main(String args[]) {
     Ids id1 = Ids.OPEN;
     System.out.println(id1.getValue());
    }
}

enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

@scottf, You probably confused because of the constructor defined in the ENUM.

Let me explain that.

When class loader loads enum class, then enum constructor also called. On what!! Yes, It's called on OPEN and close. With what values 100 for OPEN and 200 for close

Can I have different value?

Yes,

public class MyClass {
    public static void main(String args[]) {
     Ids id1 = Ids.OPEN;
     id1.setValue(2);
     System.out.println(id1.getValue());
    }
}

enum Ids {
    OPEN(100), CLOSE(200);

    private int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
    public void setValue(int value) { id = value; }
}

But, It's bad practice. enum is used for representing constants like days of week, colors in rainbow i.e such small group of predefined constants.

Solution 9 - Java

I think you're confused from looking at C++ enumerators. Java enumerators are different.

This would be the code if you are used to C/C++ enums:

public class TestEnum {
enum ids {
    OPEN,
    CLOSE,
    OTHER;

    public final int value = 100 + ordinal();
};

public static void main(String arg[]) {
    System.out.println("OPEN:  " + ids.OPEN.value);
    System.out.println("CLOSE: " + ids.CLOSE.value);
    System.out.println("OTHER: " + ids.OTHER.value);
}
};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionqrtt1View Question on Stackoverflow
Solution 1 - JavalavinioView Answer on Stackoverflow
Solution 2 - JavaPaul MorieView Answer on Stackoverflow
Solution 3 - JavaMaher AbuthraaView Answer on Stackoverflow
Solution 4 - JavaserdarView Answer on Stackoverflow
Solution 5 - JavaggrandesView Answer on Stackoverflow
Solution 6 - JavaAlcamtarView Answer on Stackoverflow
Solution 7 - JavasperlingView Answer on Stackoverflow
Solution 8 - JavaGibbsView Answer on Stackoverflow
Solution 9 - JavaCoristatView Answer on Stackoverflow