How to work with arrays inside arrays in java?

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

And let me say that I wanted to make row 3 from the array {1, 2, 3, 4}. Can I do this without assigning each individual value its value? What if it was column 2 from anArray?

I am posting this because it is rather inconvenient to do such things:

 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]; 
+4
source share
5 answers

If I understand your question correctly, here is the code for assigning row index 3 from 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]] 
+4
source

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 you want to assign a column, I'm afraid you can do it manually ...

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

This is basically an array of arrays, so we can add full arrays at a time:

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

You can use a helper method to set the 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]; } } 
0
source

Source: https://habr.com/ru/post/1490073/


All Articles