Reputation: 3883
Java serialization of multidimensional array
Is there anyway to serialize a 2D array to a string, in memory?
I'm trying to serialize a 2D array to an SQLite3 string, so I can put it in a field. The problem with the example above is that the author used fileIO, which on mobile devices is a speed killer.
Upvotes: 1
Views: 2582
Reputation: 16082
This code serialize int arrays of different sizes into String and deserialize it back into int arrays
private static final char NEXT_ITEM = ' ';
public static void main(String[] args) throws IOException {
int[][] twoD = new int[][] { new int[] { 1, 2, 2, 4, 4 }, new int[] { 3, 4, 0 }, new int[] { 9 } };
int[][] newTwoD = null; // will deserialize to this
System.out.println("Before serialization");
for(int[] arr : twoD) {
for(int val : arr) {
System.out.println(val);
}
}
String str = serialize(twoD);
System.out.println("Serialized: [" + str + "]");
newTwoD = deserialize(str);
System.out.println("After serialization");
for(int[] arr : newTwoD) {
for(int val : arr) {
System.out.println(val);
}
}
}
private static String serialize(int[][] array) {
StringBuilder s = new StringBuilder();
s.append(array.length).append(NEXT_ITEM);
for(int[] row : array) {
s.append(row.length).append(NEXT_ITEM);
for(int item : row) {
s.append(String.valueOf(item)).append(NEXT_ITEM);
}
}
return s.toString();
}
private static int[][] deserialize(String str) throws IOException {
StreamTokenizer tok = new StreamTokenizer(new StringReader(str));
tok.resetSyntax();
tok.wordChars('0', '9');
tok.whitespaceChars(NEXT_ITEM, NEXT_ITEM);
tok.parseNumbers();
tok.nextToken();
int rows = (int) tok.nval;
int[][] out = new int[rows][];
for(int i = 0; i < rows; i++) {
tok.nextToken();
int length = (int) tok.nval;
int[] row = new int[length];
out[i] = row;
for(int j = 0; j < length; j++) {
tok.nextToken();
row[j] = (int) tok.nval;
}
}
return out;
}
Upvotes: 2
Reputation: 1098
User T3hC13h has an interesting approach here: http://www.dreamincode.net/forums/topic/100732-serializingdeserializing-a-2-dimensional-array/
Upvotes: 1