0

I have a large 2D array:

int[][] matrix = new int[10000][1000];

The program needs to use frequently:

Arrays.fill(int[] a, int fromIndex, int toIndex, int val);

But sometimes it need to fill a row, and sometimes a column. For example, I can fill a row 200 by 1 from 10 to the end:

Arrays.fill(matrix[200], 10, 1000, 1);

But how to fill a column without for()? Is there a data structure that allows to perform both operation with speed, comparable to Arrays.fill() ?

2
  • @MattBall, I don't think so. The question is about filling the other dimension, i.e. matrix[0][0], matrix[1][0], etc.... Commented Jun 1, 2013 at 0:30
  • 1
    It's all the same. You have to use a for loop, either implicitly or explicitly. Arrays.fill() just happens to hide the loop from you. Commented Jun 1, 2013 at 0:31

1 Answer 1

4

if you look at the source code (which is copied below) for Arrays.fill() you will find that its only a for loop.

public static void fill(int[] a, int fromIndex, int toIndex, int val) {
    rangeCheck(a.length, fromIndex, toIndex);
    for (int i=fromIndex; i<toIndex; i++)
        a[i] = val;
}

So writing a for loop to fill the columns of the array would be the same sort of code that Arrays.fill() is giving you.

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

1 Comment

Thanks. I thought that Arrays.fill() has and advantage against for(), like System.arraycopy() has.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.