206

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?

4
  • @ScottF Do you want how to use enums ?
    – Anish B.
    Commented May 12, 2020 at 4:43
  • In the top answer, there is an enum definition. I would like an example of how that defined enum would be used in code. For example how would the defined ctor be used to create an enum instance with a specific integer value.
    – Scorb
    Commented May 12, 2020 at 22:28
  • @ScottF if I were you, instead of setting a bounty on this post I would rather post a completely new question..... or, read the documentation about enums. It seems you need to grasp some core knowledge about it ;) Commented May 17, 2020 at 14:49
  • enum ids {OPEN = 100, CLOSE};?
    – user12211554
    Commented May 17, 2020 at 18:47

9 Answers 9

320

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.

7
  • Based on your statement, would the best practice using java to create a enum of sequential integers (similar to a C++ enum), for an index into an array or something, be to write: enum Ids { NAME(0), AGE(1), HEIGHT(2), WEIGHT(3); } Thank you, -bn
    – bn.
    Commented Aug 13, 2009 at 19:35
  • Possibly, and especially if you ever serialize the integral values somewhere.
    – lavinio
    Commented Jul 24, 2011 at 0:15
  • 1
    can you please tell how to use this enum in a function? Commented Oct 20, 2015 at 10:05
  • 3
    It is lazy of the Java standards not to allow a value to be set for an enum. At least c# allows this AND is type-safe.
    – csmith
    Commented Mar 20, 2016 at 15:30
  • 3
    FWIW, C++11 now has a type-safe enum class.
    – johnthagen
    Commented Aug 28, 2017 at 19:43
98

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.

3
  • Cool. Is it possible to mix? I.e. only assign numbers to chosen Enum values. Commented Oct 19, 2016 at 8:39
  • private modifier is redundant for enum constructors Commented Jan 16, 2017 at 14:53
  • @FrederickNord - Sure. Just add a second private constructor with no args that initializes value to a (say) zero. Then include (say) DANCE in the list of values.
    – Stephen C
    Commented May 16, 2020 at 2:43
14

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.

2
  • 1
    Why is getColorValue() synchronized in the second example?
    – josaphatv
    Commented Oct 20, 2013 at 8:18
  • @josaphatv All the functionality in the second example is static, it never changes. You might want to HL_COLORS.getColorValue(HL_COLORS.YELLOW); without initializing the enum.
    – mazunki
    Commented Mar 9, 2020 at 15:50
11

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;
    }
}
8

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
5

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.

3
  • In the example you take an enum and get an int. Can you show the reverse, take an int and end up with an enum (without a explicit switch case for each value?)
    – Scorb
    Commented May 14, 2020 at 13:18
  • As per the question,I believe this is the most suitable answer. Here we have changed the default index of enum to start from 100 without defining new variable and assigning them via constructor.
    – Rahul Jain
    Commented May 14, 2020 at 19:28
  • @RahulJain I would rather use the accepted answer. It seems cleaner to me. Commented May 17, 2020 at 14:47
2

@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");
    }
}
0
 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.

0
0

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);
}
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.