logo

¿Cómo devolver una matriz en Java?

Los Arrays en Java son diferentes en implementación y uso en comparación con los de C/C++, aunque también tienen muchas similitudes. Aquí discutiremos cómo devolver una matriz en Java.

clasificación de selección

Para devolver una matriz en Java debemos cuidar los siguientes puntos:



Punto clave 1: El método que devuelve la matriz debe tener el tipo de retorno como una matriz del mismo tipo de datos que el de la matriz que se devuelve. El tipo de retorno también puede ser el habitual tipo Integer, Double, Character, String o objetos de clase definidos por el usuario.

// Method returning an integer array. int[] methodName() {...}>
// Method returning a String array. String[] methodName() {...}>
// Method returning an array of objects of class named Students. Students[] methodName() {...}>

Punto clave 2: Los modificadores de acceso deben usarse con precisión considerando el uso del método y la matriz de retorno. También deben tenerse en cuenta las declaraciones estáticas y no estáticas.

// Using public access modifier and static to call the method from a static class, method or block. public static char[] methodName() {...}>

Punto clave 3: Debe haber una matriz de variables del mismo tipo de datos o algo similar en la llamada al método para manejar la matriz que se devuelve. Por ejemplo, una matriz de enteros devuelta por cualquier método se puede almacenar de la siguiente manera.



int[] storage = methodReturningArray();>

Implementación:

Para comprender mejor esto, podemos analizar algunos tipos diferentes de escenarios en los que podemos devolver matrices. Aquí consideraremos tres ejemplos de escenarios.

  • Caso 1: matrices integradas simples
  • Caso 2: conjunto de objetos
  • Caso 3: Devolver matrices multidimensionales

Caso 1: Devolver una matriz de números enteros (tipo de datos incorporado) en Java



Se puede devolver cualquier matriz de tipo de datos incorporado, ya sea entero, carácter, flotante, doble, simplemente use declaraciones de devolución teniendo en cuenta los puntos enumerados anteriormente.

Ejemplo

Java




// Java Program to Illustrate Returning> // simple built-in arrays> // Importing input output classes> import> java.io.*;> // Main class> class> GFG {> >// Method 1> >// Main driver method> >public> static> void> main(String[] args)> >{> >// An integer array storing the returned array> >// from the method> >int>[] storage = methodReturningArray();> >// Printing the elements of the array> >for> (>int> i =>0>; i System.out.print(storage[i] + ' '); } // Method 2 // Returning an integer array public static int[] methodReturningArray() { int[] sample = { 1, 2, 3, 4 }; // Return statement of the method. return sample; } }>

>

matemáticas.pow java
>

Producción

1 2 3 4>

Caso 2: Devolver una matriz de objetos en java

Esto se hace exactamente de manera similar en el caso de devolver matrices de tipos de datos integrados.

Ejemplo

Java




// Java Program to Illustrate Returning> // an array of objects in java> // Importing all input output classes> import> java.io.*;> // Class 1> // Helper class> // Courses whose objects are returned as an array> class> Courses {> >String name;> >int> modules;> >// Constructor to instantiate class objects.> >public> Courses(String n,>int> m)> >{> >// This keyword refers to current instance itself> >this>.name = n;> >this>.modules = m;> >}> }> // Class 2> // Main class> class> GFG {> >// Method 1> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Calling the method for returning an array of> >// objects of the Courses class.> >Courses[] sample = methodReturningArray();> >// Printing the returned array elements.> >for> (>int> i =>0>; i System.out.print(sample[i].name + ' - ' + sample[i].modules + ' modules '); } // Method 2 // Note that return type is an array public static Courses[] methodReturningArray() { // Declaring Array of objects of the Courses class Courses[] arr = new Courses[4]; // Custom array of objects arr[0] = new Courses('Java', 31); arr[1] = new Courses('C++', 26); arr[2] = new Courses('DSA', 24); arr[3] = new Courses('DBMS', 12); // Statement to return an array of objects return arr; } }>

>

>

Producción

inicializador de diccionario c#
Java - 31 modules C++ - 26 modules DSA - 24 modules DBMS - 12 modules>

Caso 3: Devolver matrices multidimensionales

matrices multidimensionales en java Se puede decir que es una matriz de matrices dentro de matrices. La forma más simple puede ser una matriz bidimensional. Tienen sus tallas y declaración según sus tallas. A continuación se demuestra el retorno de una matriz bidimensional que tiene un enfoque muy similar a las matrices unidimensionales.

Ejemplo

Java




// Java Program to Illustrate Returning> // Multi-dimensional Arrays> // Importing input output classes> import> java.io.*;> // Main class> class> GFG {> >// Method 1> >// Main driver method> >public> static> void> main(String[] args)> >{> >// An integer 2D array storing the> >// returned array from the method> >int>[][] storage = methodReturningArray();> >// Printing the elements of the array> >// using nested for loops> >for> (>int> i =>0>; i for (int j = 0; j 0].length; j++) System.out.print(storage[i][j] + ' '); System.out.println(); } } // Method 2 // Returning an integer array public static int[][] methodReturningArray() { // Custom 2D integer array int[][] sample = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Return statement of the method return sample; } }>

largo para encordar
>

>

Producción

1 2 3 4 5 6 7 8 9>