If you want to convert the whole 2d-array into a single String, you could use a CSV-type encoding, but you'd have to protect any special character (typ. the comma-separator) in order not to mess up field separation. A quick (and dirty?) way to do it would be to use enc = URLEncoder.encode(val, "UTF-8")
on each value, and then back with val = URLDecoder.decode(enc, "UTF-8")
.
You would also have to use another separator (e.g. \n
) to separate lines:
String write(MyENum[][] myArray) {
String res = "";
for (int iRow = 0; iRow < myArray.length; iRow++) {
for (int iCol = 0; iCol < myArray[iRow].length; iCol++)
res += URLEncoder.encode(myArray[iRow][iCol].name(), "UTF-8")+",";
res += "\n";
}
}
(I'll let it to you not to add the extra ","
at the end of each line). Then, to read back:
MyEnum[][] read(String res) {
String[] rows = res.split("\n");
MyEnum[][] myArray = new MyEnum[rows.length][];
for (int iRow; iRow < rows.length; iRow++) {
String[] cols = rows[iRow].split(",");
myArray[iRow] = new MyEnum[cols.length];
for (int iCol = 0; iCol < cols.length; iCol++)
myArray[iRow][iCol] = MyEnum.valueOf(URLDecoder.decode(cols[iCol], "UTF-8"));
}
return myArray;
}
That is all based on the fact that there are name()
and valueOf()
methods available in your enum to make the transformation, as @sean-f showed you in the post he linked.