1

I already know how to create an array of different lengths in Java if I know the format of the array at compile time.
Ex:

char[][] array = { { 'a', 'b', 'c'}, {'d'}, {'e', 'f'}}; //etc....

The problem is that i need that made at runtime. I don't know the size I'll need for the array at compile time but I'll know it at runtime.

The objective here is to make in java (and have the advantages of arrays in java (like the .length)) to make what in C would be:

char[][] arrayC = malloc(outerArraySize);
for(int i = 0; i < outerArraySize; i++){
    arrayC[i] = malloc(innerArraySize[i]);
}

This C code was made here ad-hoc so it may contain errors but it's purpose is just to clarify the question message.

Anyway of doing this properly in Java?

1 Answer 1

5

Sure - just use an array creation expression:

char[][] array = new char[outerArraySize][];
for (int i = 0; i < outerArraySize; i++) {
    array[i] = new char[innerArraySize[i]];
}

You might also want to consider using strings instead of character arrays, depending on the situation.

Sign up to request clarification or add additional context in comments.

3 Comments

Gosh oh holly that was fast! I tried something somewhat like that previously (java 5 or java 6) and I was having stuff like syntax error or so and I didn't read any news about it changing.
@brunoais: It hasn't changed. That's worked since Java 1. You should look very carefully at the syntax error.
yeah... I didn't even try recently :D. I just went though and did the question because I knew it didn't work previously. Oh! and BTW, I just wanted a direct translation to C and I thought that the char[][] would be a good example to show my intent (as there's no such thing as a string in C, only a char[]). I'm using and array of an object I made myself, so don't worry ;)

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.