multidimensional example dimensional bidimensional array java arrays multidimensional-array

example - Obtener la longitud de la matriz de una matriz 2D en Java



java array example multidimensional (7)

Si tienes esta matriz:

String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}}, {{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};

Puedes hacerlo:

example.length;

= 2

example[0].length;

= 2

example[1].length;

= 2

example[0][1].length;

= 3

example[1][0].length;

= 4

Necesito obtener la longitud de una matriz 2D para la fila y la columna. Lo he hecho con éxito, usando el siguiente código:

public class MyClass { public static void main(String args[]) { int[][] test; test = new int[5][10]; int row = test.length; int col = test[0].length; System.out.println(row); System.out.println(col); } }

Esto imprime 5, 10 como se esperaba.

Ahora eche un vistazo a esta línea:

int col = test[0].length;

Tenga en cuenta que en realidad tengo que hacer referencia a una fila en particular, para obtener la longitud de la columna. Para mí, esto parece increíblemente feo. Además, si la matriz se definió como:

test = new int[0][10];

Entonces el código fallaría al tratar de obtener la longitud. ¿Hay alguna manera diferente (más inteligente) de hacer esto?


Considerar

public static void main(String[] args) { int[][] foo = new int[][] { new int[] { 1, 2, 3 }, new int[] { 1, 2, 3, 4}, }; System.out.println(foo.length); //2 System.out.println(foo[0].length); //3 System.out.println(foo[1].length); //4 }

Las longitudes de columna difieren por fila. Si está respaldando algunos datos mediante una matriz 2D de tamaño fijo, proporcione getters a los valores fijos en una clase contenedora.


Java le permite crear "matrices irregulares" donde cada "fila" tiene diferentes longitudes. Si sabes que tienes una matriz cuadrada, puedes usar tu código modificado para protegerte contra una matriz vacía como esta:

if (row > 0) col = test[0].length;


No hay una manera más limpia en el nivel de idioma porque no todas las matrices multidimensionales son rectangulares. A veces, las matrices dentadas (diferentes longitudes de columna) son necesarias.

Puede crear fácilmente su propia clase para abstraer la funcionalidad que necesita.

Si no está limitado a las matrices, entonces quizás algunas de las diversas clases de colección también funcionarían, como un Multimap .


Pruebe este siguiente programa para 2d array en java:

public class ArrayTwo2 { public static void main(String[] args) throws IOException,NumberFormatException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int[][] a; int sum=0; a=new int[3][2]; System.out.println("Enter array with 5 elements"); for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { a[i][j]=Integer.parseInt(br.readLine()); } } for(int i=0;i<a.length;i++) { for(int j=0;j<a[0].length;j++) { System.out.print(a[i][j]+" "); sum=sum+a[i][j]; } System.out.println(); //System.out.println("Array Sum: "+sum); sum=0; } } }


Una matriz 2D no es una cuadrícula rectangular. O tal vez mejor, no existe una matriz 2D en Java.

import java.util.Arrays; public class Main { public static void main(String args[]) { int[][] test; test = new int[5][];//''2D array'' for (int i=0;i<test.length;i++) test[i] = new int[i]; System.out.println(Arrays.deepToString(test)); Object[] test2; test2 = new Object[5];//array of objects for (int i=0;i<test2.length;i++) test2[i] = new int[i];//array is a object too System.out.println(Arrays.deepToString(test2)); } }

Salidas

[[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]] [[], [0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]

Las matrices test y test2 son (más o menos) lo mismo.


public class Array_2D { int arr[][]; public Array_2D() { Random r=new Random(10); arr = new int[5][10]; for(int i=0;i<5;i++) { for(int j=0;j<10;j++) { arr[i][j]=(int)r.nextInt(10); } } } public void display() { for(int i=0;i<5;i++) { for(int j=0;j<10;j++) { System.out.print(arr[i][j]+" "); } System.out.println(""); } } public static void main(String[] args) { Array_2D s=new Array_2D(); s.display(); } }