203

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?

0xCursor
  • 2,242
  • 4
  • 15
  • 33
qrtt1
  • 7,746
  • 8
  • 42
  • 62
  • @ScottF Do you want how to use enums ? – Anish B. May 12 '20 at 04: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 May 12 '20 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 ;) – lealceldeiro May 17 '20 at 14:49
  • `enum ids {OPEN = 100, CLOSE};`? –  May 17 '20 at 18:47

9 Answers9

317

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.

Bumptious Q Bangwhistle
  • 4,689
  • 2
  • 34
  • 43
lavinio
  • 23,931
  • 5
  • 55
  • 71
  • 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. Aug 13 '09 at 19:35
  • Possibly, and especially if you ever serialize the integral values somewhere. – lavinio Jul 24 '11 at 00:15
  • 1
    can you please tell how to use this enum in a function? – Bugs Happen Oct 20 '15 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 Mar 20 '16 at 15:30
  • 3
    FWIW, C++11 now has a type-safe `enum class`. – phoenix Aug 28 '17 at 19:43
  • Ok so now how do I use this enum? I have an int that is value 100, how to I create an enum with value OPEN from it? How do I use this ctor(?) that you defined here. Please give an example. – Scorb May 10 '20 at 19:34
  • As per the question, I think the user wants to change the default index of enum. But here what we have defined the new variable and assigning its value via constructor. Even after above code.. if we try to print OPEN.value then it will still return as 0 – Rahul Jain May 14 '20 at 19:34
97

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.

Paul Morie
  • 15,528
  • 9
  • 52
  • 57
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.

Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103
  • 1
    Why is `getColorValue()` synchronized in the second example? – josaphatv Oct 20 '13 at 08: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 Mar 09 '20 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;
    }
}
takrl
  • 6,356
  • 3
  • 60
  • 69
serdar
  • 111
  • 1
  • 2
7

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
ggrandes
  • 2,067
  • 22
  • 16
4

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.

Alcamtar
  • 1,478
  • 13
  • 19
  • 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 May 14 '20 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 May 14 '20 at 19:28
  • @RahulJain I would rather use the accepted answer. It seems cleaner to me. – lealceldeiro May 17 '20 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");
    }
}
sperling
  • 56
  • 7
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.

Gibbs
  • 21,904
  • 13
  • 74
  • 138
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);
}
};
Coristat
  • 11
  • 4