4

Let's say I have an int[][] anArray = new int[4][4];

And let's say that I wanted to make row 3 of anArray {1, 2, 3, 4}. Could I do that without manually assigning each individual value its value? What if it was column 2 of anArray?

I'm posting this because it's rather inconvenient to do stuff like this:

int[][] foo = new int[bar][baz];
//
//Code that uses other columns of foo
//
for (int n=0; n < bar; n++)
    foo[n][1] = bin[n];
2
  • 3
    A suggestion: foo[2] = new int[]{1,2,3,4};. Commented Jul 6, 2013 at 21:59
  • I'll make a suggestion since I won't be answering your question, really. The answer is, "Don't". Instead, use collection classes such as ArrayList or HashMap. Commented Jul 6, 2013 at 22:25

5 Answers 5

4

If I understand your question correctly, here is the code to assign row index 3 of anArray as {1,2,3,4} without loops:

int[][] anArray = new int[4][4];
anArray[3] = new int[] {1,2,3,4};
System.out.println(Arrays.deepToString(anArray));

Output:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 2, 3, 4]]
Sign up to request clarification or add additional context in comments.

1 Comment

@Keyser you're welcome. There's always some possibility of semantic confusion about indexing since it starts at 0, so of course as you imply "row 3" might be anArray[2] - I just chose anArray[3] for reasons beyond my own understanding :)
0

If you want to assign the entire row of a two-dimensional array to another (one-dimensional) array, you can simply do

int[][] foo = new int [3][3];
int[] bin={1,2,3};
foo[1] = bin;

If want to assign the column though, I am afraid that you can only do it manually...

Comments

0
anArray[3] = new int [] {1, 2, 3, 4}

Comments

0

It is basically an array of arrays and so we can add full arrays in one go:

int[][] array = new int[4][4];
for (int i = 0; i < array.length; i++) {
    array[i] = new int[] { 1, 2, 3, 4 };
}

Comments

0

You can use a helper method to set a column:

public class MatrixTest {

  public static void main(String... args) {
    Integer[][] target = new Integer[3][2];
    setMatrixColumn( target, 1, new Integer[]{ 1, 1, 1 } );

    System.out.println( Arrays.deepToString( target ) );
  }

  public static <T> void setMatrixColumn(T[][] matrix, int index, T[] values) {
    for ( int i = 0; i < values.length; i++ )
      matrix[i][index] = values[index];
  }
}

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.