Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #31590 > unrolled thread

Re: enum, what is it good for?

Started byTassilo Horn <tsdh@gnu.org>
First post2015-04-21 05:37 +0200
Last post2015-04-21 05:37 +0200
Articles 1 — 1 participant

Back to article view | Back to comp.lang.java.programmer

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: enum, what is it good for? Tassilo Horn <tsdh@gnu.org> - 2015-04-21 05:37 +0200

#31590 — Re: enum, what is it good for?

FromTassilo Horn <tsdh@gnu.org>
Date2015-04-21 05:37 +0200
SubjectRe: enum, what is it good for?
Message-ID<87a8y2w3rm.fsf@gnu.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web