Java array of enum values

79,914

Solution 1

You are missing one tiny part of the Array declaration.

_machines = new Machine[]{Machine.a, Machine.b};

Solution 2

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

_machines = new Machine[size];
Share:
79,914
Dustin Sun
Author by

Dustin Sun

Programmer turned Mortgage Loan Officer. Need mortgage loan in Florida?

Updated on October 28, 2020

Comments

  • Dustin Sun
    Dustin Sun over 3 years

    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!

  • Dustin Sun
    Dustin Sun over 13 years
    Working. Thank you so much for your quick reply.
  • ceving
    ceving almost 11 years
    Machine.a, Machine.b can be simplified to a, b. The prefix is redundant, because an array of Machine enums can only contain Machine enums.
  • Pulkit Agarwal
    Pulkit Agarwal almost 10 years
    @ceving this does not work. Is there something I need to do to make this happen? I do not want to write "Machine" every time.
  • jjnguy
    jjnguy almost 10 years
    @PulkitAgarwal have a look at static imports. docs.oracle.com/javase/1.5.0/docs/guide/language/…
  • Leo Nikkilä
    Leo Nikkilä over 7 years
    Note that this is different from OP’s case. This initialises an array with null values, whereas OP is asking about initialising it with predefined non-null values.
  • Kostanos
    Kostanos about 5 years
    Ho do I find not the position of some enum on this array? _machines.indexOf(Machine.a) doesn't work :(