2

I was wondering what would be the way to store multiple values in enum class?

I tried

public enum name { 
  James(1,2,3)
  Taylor(2,3,4)
  Mary(5,6,7);
}

but this throws me an error.

3
  • FYI, enum names should follow the usual class naming conventions. E.g., EnumName. Commented Oct 9, 2018 at 23:32
  • 4
    sorry if this seems rude but docs.oracle.com/javase/tutorial/java/javaOO/enum.html Commented Oct 9, 2018 at 23:34
  • 1
    I agree with giorgia: step one is to do research. Trying to invent your own syntax is most often an inefficient approach to programming. Commented Oct 10, 2018 at 0:45

4 Answers 4

4

Regarding this, an enum acts just like a normal class: you will need a constructor.

private Name(int a, int b, int c) {
    // Define some fields and store a b and c into them
}

Notice that within the class body, the enum constants must be defined first, and then the optional fields, constructors and methods:

enum Name {
    ENUM_CONSTANT_1, ENUM_CONSTANT_2;

    int field;

    Name() { ... }

    public void someMethod() { ... }

}

Note: You should follow the Java Naming Conventions: class names (including enum names) always start with uppercase.

Sign up to request clarification or add additional context in comments.

Comments

3

Commas must be between all declared enum instances.

Like any constructor call, the arguments must match a constructor signature. Declare a constructor to accept three parameters. You'll probably want to assign them to fields and you may want to provide getters.

public enum Name { 
    James(1,2,3),
    Taylor(2,3,4),
    Mary(5,6,7);

    private int a, b, c;

    Name(int a, int b, int c) {
        // Assign to instance variables here
    }
    // Provide getter methods here.
}

Comments

0

You need a name constructor. It needs to take at least three ints. It could be variadic. Like,

public enum name {
    James(1, 2, 3), Taylor(2, 3, 4), Mary(5, 6, 7);
    int[] arr;
    private name(int... arr) {
        this.arr = arr;
    }
}

Comments

0
public class Test{

 enum EnumName{

    James(1,2,3),
    Taylor(2,3,4),
    Mary(5,6,7);

    private int a,b,c;

    EnumName(int a,int b,int c){
       this.a=a;
       this.b=b;
       this.c=c;
    }
 }

 public static void main(String []args){
    EnumName n = EnumName.James; 
    System.out.println(n.a);
 }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.