Reputation: 63
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.
Upvotes: 2
Views: 10615
Reputation: 563
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);
}
}
Upvotes: 0
Reputation: 22977
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.
Upvotes: 4
Reputation: 178253
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.
}
Upvotes: 3
Reputation: 201439
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;
}
}
Upvotes: 0