9

Our homework assignment asks us to use a jagged array to store the values of a two dimensional boolean matrix. Is there a built in java class for the jagged array or am I going to have to manually create it with an Array of ArrayLists?

2 Answers 2

16

In Java, a 2D array is an array of 1D array objects. Each 1D array can have different length, which means that you get jagged arrays out of the box.

For example, the following is perfectly valid Java, and prints out 3 5 3 4:

    int x[][] = {{0,1,2,3,4},{0,1,2},{0,1,2,3}};
    System.out.println(x.length);
    System.out.println(x[0].length);
    System.out.println(x[1].length);
    System.out.println(x[2].length);
Sign up to request clarification or add additional context in comments.

2 Comments

So if i need to add more elements to these indiviuals arrays i would have to resize x[1] for example instead of just x?
@Chris: Yes. For example x[1] = Arrays.copyOf(x[1], newLength);
0

It actually sounds like you might want a sparse matrix implementation. You can get much better performance out of it if you are having to modify the matrix. Array copy operations are pretty expensive. Sparse matrices / arrays in Java

Comments

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.