Jojo
Jojo

Reputation: 41

Java array with enums

I experimented a little with enums and arrays in Java:

enum animals
  {CAT, DOG, COW, BIRD, POTATO}

To get this into an array I simply do this...

animals[] creatures = {animals.CAT, animals.POTATO};

But now if I have to define bigger entries, I thought it would be useful if I can just type in the enumeration without animals.XXX, like I also do in C++

animals[] creatures = {CAT, POTATO, BIRD, CAT, CAT, POTATO, COW...}

So I just wondered if this is possible in any way, and why if not?

Upvotes: 1

Views: 11289

Answers (4)

Alireza Fattahi
Alireza Fattahi

Reputation: 45485

Below should do it

animals[] creatures = {animal.CAT, animal.POTATO, animal.BIRD, CAT};

Upvotes: 1

Makoto
Makoto

Reputation: 106430

While there are other solutions that will work, you don't have to really go through any of that. What you can do instead is use the values() array to pull in all of the present values attached to the array instead.

That is, if you really want to have an array called creatures that contains all entries of your enum, you can express that as this:

// Classes, interfaces, and enums should start with an upper case
Animals[] creatures = Animals.values();

If you add a new entry to the enum it will be automatically pulled in through values().

Upvotes: 2

Andreas
Andreas

Reputation: 159096

First off, the enum should be named Animals, since types should start with an uppercase letter.

The reason you have to qualify the values in the array initializer, is because each value of the initializer is a full-blown expression.

int x = <expression>;
int[] x = {<expression>, <expression>, ...};
Animals x = <expression>;
Animals[] x = {<expression>, <expression>, ...};

The only place an enum value doesn't need to be qualified, is in a switch statement, because the value of a case must be a constant, not an expression:

switch (animal) {
    case CAT:
        // code
        break;
    case DOG:
        // code
        break;
}

Outside of that you have to qualify, unless of course you import the enum values using import static.

Upvotes: 1

Tunaki
Tunaki

Reputation: 137084

Java mandates that you use the fully classified name to use it. For standard classes, this is generally done by importing a package with import name.of.package and then using the simple name of the class. For static fields, like enum constants, you can use static imports.

import static animals.CAT;
import static animals.POTATO;
import static animals.BIRD;
import static animals.COW;

// ...

animals[] creatures = {CAT, POTATO, BIRD, CAT, CAT, POTATO, COW...};

You could also use

import static animals.*;

avoiding the need to import every animals, but note that the first construct is generally considered better than the second one.

Upvotes: 4

Related Questions