Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #31590
| From | Tassilo Horn <tsdh@gnu.org> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: enum, what is it good for? |
| Date | 2015-04-21 05:37 +0200 |
| Organization | University Koblenz-Landau Campus Koblenz |
| Message-ID | <87a8y2w3rm.fsf@gnu.org> (permalink) |
| References | <enum-20150421042614@ram.dialup.fu-berlin.de> |
ram@zedat.fu-berlin.de (Stefan Ram) writes:
> I never use »enum«, so I thought that maybe I should give it
> a try. I wrote:
>
> enum Square
> { O( -1 ), Z( 0 ), X( 1 );
> private final int state;
> Square( final int state ){ this.state = state; }
> public int value() { return state; }}
>
> But I was not feeling well with this (because I though O
> might have the field »state« /and/ also another »internal«
> hidden value, which seems to be redundant) and rewrote it
> into:
Indeed, that's the case. But as long as you want a successive
numbering, you can compute that with ordinal(). The ordinals of enum
constants tell the order of their declaration starting with 0.
enum Square {
O, Z, X;
public int getValue() { return ordinal() - 1; }
}
> class Square
> { public static Square O = new Square( -1 );
> public static Square Z = new Square( 0 );
> public static Square X = new Square( 1 );
> private final int state;
> private Square( final int state ){ this.state = state; }
> public int value() { return state; }}
>
> I can use »Square.X« with both of these notations.
>
> So, is there any reason to prefer »enum« to »class«?
You can use enum constants in a switch statement:
switch (mySquare) {
case O: ...
case Z: ...
case X: ...
}
You couldn't do that if Square was a class.
Bye,
Tassilo
Back to comp.lang.java.programmer | Previous | Next | Find similar | Unroll thread
Re: enum, what is it good for? Tassilo Horn <tsdh@gnu.org> - 2015-04-21 05:37 +0200
csiph-web