Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array of enum values

Tags:

Machine is defined as public enum Machine{...}

_machines is defined as private Machine[] _machines;

Don't know why this doesn't work:

_machines = {Machine.a, Machine.b}; 

error message:

illegal start of expression

Thank you guys!

like image 472
Dustin Sun Avatar asked Nov 17 '10 16:11

Dustin Sun


People also ask

Can we have array of enum in java?

You can iterate through an enum to access its values. The static values() method of the java. lang. Enum class that all enums inherit gives you an array of enum values.

How do you declare an array of enums?

This way I can write a functions in which I can pass the array index into for setting particuler values of the enum. Updated: Here is an example of what I am wanting to do. [flag] enum1(value1=0, value2=1, value3=2, value4=4...)

How do you iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.

What are enumerations in java?

An enumeration (enum for short) in Java is a special data type which contains a set of predefined constants. You'll usually use an enum when dealing with values that aren't required to change, like days of the week, seasons of the year, colors, and so on.


2 Answers

You are missing one tiny part of the Array declaration.

_machines = new Machine[]{Machine.a, Machine.b}; 
like image 142
jjnguy Avatar answered Oct 11 '22 16:10

jjnguy


This can also be declared empty at first if you give it a size.

_machines = new Machine[size]; 
like image 22
JG007 Avatar answered Oct 11 '22 16:10

JG007