Snake
Snake

Reputation: 14658

Set of constants that I can iterate through

I often run into a situation where I need to define a set of constants and I need to loop through them. Lets say Card Suit where I need to display the list of available suits to the user.

The two options I see are enums or static int. But the thing is that when I need to iterate through the list, I end up using enum with values() and Ordinal(). Many people say using these are bad and you should go back to static int.

How do you guys code a set of constants where you need you iterate through them? What's the best practice?

Thanks

Upvotes: 2

Views: 736

Answers (1)

Andy Thomas
Andy Thomas

Reputation: 86459

It's okay to use the values() method. In fact, the Java tutorial for enums mentions this explicitly:

The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                  p, p.surfaceWeight(mass));
}

Enums provide some advantages over constant ints, such as stronger type-checking. But if you absolutely had to code-tune, and were certain that you were not optimizing prematurely, you could use constant ints and an array containing them. Disclaimer: I'm not recommending this for usual practice. Please don't do this by default.

private static final int SUIT_SPADES = 1;
private static final int SUIT_CLUBS = 2;
private static final int SUIT_HEARTS = 4;
private static final int SUIT_DIAMONDS = 8;

private static final int[] SUITS = new int[] { 
   SUIT_SPADES, SUIT_CLUBS, SUIT_HEARTS, SUIT_DIAMONDS };

...
for ( int suit : SUITS ) { ... }

Upvotes: 6

Related Questions