eaglgenes101
eaglgenes101

Reputation: 169

How to work with arrays within arrays in java?

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];

Upvotes: 4

Views: 165

Answers (5)

Raffaele
Raffaele

Reputation: 20885

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];
  }
}

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114787

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 };
}

Upvotes: 0

Mena
Mena

Reputation: 48404

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]]

Upvotes: 4

Stefan Haustein
Stefan Haustein

Reputation: 18803

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

Upvotes: 0

user000001
user000001

Reputation: 33327

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...

Upvotes: 0

Related Questions