user47
user47

Reputation: 131

How can I expand the entries of a 2d array in Java?

How can I dynamically allocate space for n entries, if I already know the number of columns of a 2d array? I wanted to know the way to doing this without using Lists but I cannot find anything. Any help?

Upvotes: 0

Views: 130

Answers (2)

WJS
WJS

Reputation: 40034

Try this.


int rows = 200;
int cols = 300;

int[][] mat = new int[rows][cols];

You can also read in the row and col from a file, allocate your array and then continue reading the values to populate the array.

The difficulty comes when you don't know the size of the array. So you need to first, pre allocate the array which is a guess. Then read in as much as you can and continually increase the size until you are done reading.

Upvotes: 2

Pulkit Sharma
Pulkit Sharma

Reputation: 28

You can use Arrays.copyOf() function.

Let's say you want to increase size of 4th row in your 2d array with 6 rows.

you could simply, say myArray[3] = Arrays.copyOf(myArray[3], newSize);

Upvotes: 0

Related Questions