Is it possible to get ENUM name and labels together? Like:
[
{"COMBUSTIVEL", "Combustível"},
{"TROCADEOLEO", "Troca de Óleo"},
{"PNEUDIANTEIRO", "Pneu Dianteiro"},
{"PNEUTRASEIRO", "Pneu Traseiro"},
{"CORRENTE", "Corrente"},
{"RELACAO", "Relação"}
]
I'm using Spring MVC, but I think it is irrelevant.
I tried to override the toString()
method, but unfortunately it did not work.
My code:
public enum Categoria {
COMBUSTIVEL("Combustível"),
TROCADEOLEO("Troca de óleo"),
PNEUDIANTEIRO("Pneu dianteiro"),
PNEUTRASEIRO("Pneu traseiro"),
CORRENTE("Corrente"),
RELACAO("Relação");
private String label;
Categoria(String item){
this.label = item;
}
public String getLabel(){
return this.label;
}
@Override
public String toString() {
return this.label;
}
public String[][] getList(){
Categoria[] values = Categoria.values();
return ?;
}
}
The results is:
[
"COMBUSTIVEL",
"TROCADEOLEO",
"PNEUDIANTEIRO",
"PNEUTRASEIRO",
"CORRENTE",
"RELACAO"
]
This can be done like this:
public static String[][] getList(){
Categoria[] values = Categoria.values();
String[][] result = new String[values.length][2];
for (int i = 0; i < values.length; ++i) {
String[] pair = {values[i].name(), values[i].toString()};
result[i] = pair;
}
return result;
}
Why a 2D array? Your solution may work OK for storing, but not as good for retrieving values. A Map will be more effective. It would also allow to store the same enumeration multiple times without restriction unless you add strenuous code to prevent it.
The question asks for
2D
array: the return type of thegetList
isString[][]
.It is better to ask OP. I guess the API here is consumed by some client that needs an array.