1

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.

1
  • 1
    I had the exact same problem. Thanks for asking. Commented Feb 13, 2012 at 6:58

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

User T3hC13h has an interesting approach here: http://www.dreamincode.net/forums/topic/100732-serializingdeserializing-a-2-dimensional-array/

1 Comment

That seems to work, however it makes it difficult to get it back to byte array.

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.