tags:

views:

1462

answers:

2

Hi, I use the enum make a few constants:

enum ids {OPEN, CLOSE};

the OPEN'valuse is zero, but I wanna it as 100. Is it possible?

+8  A: 

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
+4  A: 

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://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html for more.

lavinio
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