En Java, una matriz es una estructura de datos que almacena una colección de elementos del mismo tipo de tamaño fijo. Para determinar la longitud o el tamaño de una matriz en Java, podemos utilizar diferentes métodos.
Método 1: enfoque ingenuo para encontrar la longitud de la matriz Java
El método ingenuo se utiliza para el bucle para determinar el tamaño/longitud de las matrices de tipo char, entero y cadena.
A continuación se muestra la implementación del enfoque anterior:
Java
// Java program to demonstrate for loop> // to calculate size/length of all type of arrays> > import> java.util.*;> > public> class> Main {> >public> static> void> main(String[] argv)> >{> > >// Creating Arrays and Populating them> >char>[] char_arr = {>'a'>,>'b'>,>'c'>,>'d'>,>'e'> };> >int>[] int_arr = {>1>,>2>,>3>,>4>,>5>,>6>,>7> };> >String[] str_arr> >= {>'GFG'>,>'GEEKS'>,>'GEEKSFORGEEKS'> };> > >int> ci =>0>, ii =>0>, si =>0>;> > >// print char array> >System.out.print(>'Char Array: [ '>);> >for> (>char> c : char_arr) {> >System.out.print(>'''> + c +>'' '>);> >ci++;> >}> >System.out.println(>']'>);> > >// print integer array> >System.out.print(>'Integer Array: [ '>);> >for> (>int> c : int_arr) {> >System.out.print(c +>' '>);> >ii++;> >}> >System.out.println(>']'>);> > >// print string array> >System.out.print(>'String Array: [ '>);> >for> (String c : str_arr) {> >System.out.print(>'''> + c +>'' '>);> >si++;> >}> >System.out.println(>']
'>);> > >// print the size/length of all arrays> >System.out.println(>'Size of char array = '> + ci);> >System.out.println(>'Size of integer array = '> + ii);> >System.out.println(>'Size of string array = '> + si);> >}> }> > // This code is contributed by Susobhan Akhuli> |
>
>Producción
Char Array: [ 'a' 'b' 'c' 'd' 'e' ] Integer Array: [ 1 2 3 4 5 6 7 ] String Array: [ 'GFG' 'GEEKS' 'GEEKSFORGEEKS' ] Size of char array = 5 Size of integer array = 7 Size of string array = 3>
La complejidad del método anterior.
Complejidad del tiempo: O(N), donde N es el tamaño de la matriz.
Espacio Auxiliar: O(1)
Método 2: uso del método length() para encontrar el tamaño de la matriz de Java
Hay un longitud campo disponible en la matriz que se puede utilizar para encontrar la longitud o el tamaño de la matriz.
longitud.matriz: length es una variable final aplicable a las matrices. Con la ayuda de la variable de longitud, podemos obtener el tamaño de la matriz.
Ejemplos:
int size = arr[].length; // length can be used // for int[], double[], String[] // to know the length of the arrays.>
A continuación se muestra la ilustración de cómo obtener la longitud de una matriz [] en Java usando la variable de longitud:
Ejemplo 1:
Java
// Java program to illustrate> // how to get the length of the array> > public> class> Test {> >public> static> void> main(String[] args)> >{> > >// Here array is the> >// array name of int type> >int>[] array =>new> int>[>4>];> > >System.out.println(>'The size of '> >+>'the array is '> >+ array.length);> >}> }> |
>
>Producción
The size of the array is 4>
Ejemplo 2:
Java
// Java program to illustrate> // how to get the length of the array> > public> class> Test {> >public> static> void> main(String[] args)> >{> > >// Here str is the array name> >// of String type.> >String[] str = {>'GEEKS'>,>'FOR'>,>'GEEKS'> };> > >System.out.println(>'The size of '> >+>'the array is '> + str.length);> >}> }> |
>
>Producción
iterador java para mapa
The size of the array is 3>
La complejidad del método anterior.
Complejidad del tiempo: O(1)
Espacio Auxiliar: O(1)
Método 3: usar size() para encontrar el tamaño de la matriz Java
Alternativamente, podemos utilizar el tamaño() método de la java.util.ArrayList clase, que devuelve el número de elementos de la lista.
el Ejemplo 1:
Java
// Java program to demonstrate> // size() method> // for Integer value> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)> >{> > >// Creating object of ArrayList> >ArrayList arrlist> >=>new> ArrayList();> > >// Populating arrlist1> >arrlist.add(>1>);> >arrlist.add(>2>);> >arrlist.add(>3>);> >arrlist.add(>4>);> >arrlist.add(>5>);> > >// print arrlist> >System.out.println(>'Array: '> + arrlist);> > >// getting total size of arrlist> >// using size() method> >int> size = arrlist.size();> > >// print the size of arrlist> >System.out.println(>'Size of array = '> + size);> >}> }> > // This code is contributed by Susobhan Akhuli> |
>
>Producción
Array: [1, 2, 3, 4, 5] Size of array = 5>
Ejemplo 2:
Java
// Java program to demonstrate> // size() method> // for String value> > import> java.util.*;> > public> class> GFG1 {> >public> static> void> main(String[] argv)> >{> > >// Creating object of ArrayList> >ArrayList arrlist =>new> ArrayList();> > >// Populating arrlist1> >arrlist.add(>'GFG'>);> >arrlist.add(>'GEEKS'>);> >arrlist.add(>'GEEKSFORGEEKS'>);> > >// print arrlist> >System.out.println(>'Array: '> + arrlist);> > >// getting total size of arrlist> >// using size() method> >int> size = arrlist.size();> > >// print the size of arrlist> >System.out.println(>'Size of array = '> + size);> >}> }> > // This code is contributed by Susobhan Akhuli> |
>
>Producción
Array: [GFG, GEEKS, GEEKSFORGEEKS] Size of array = 3>
La complejidad del método anterior.
Complejidad del tiempo: O(1)
Espacio Auxiliar: O(1)
Método 4: usar Stream API para verificar la longitud de la matriz de Java
Java 8 introdujo el API de transmisión , que nos permite realizar operaciones sobre arrays utilizando programación funcional. El contar() método de la Arroyo La clase se puede utilizar para contar el número de elementos en una matriz.
A continuación se muestra la implementación del enfoque anterior:
Java
// Java program to demonstrate Stream.count()> // method to calculate size/length of> // different arrays> import> java.util.*;> > // Driver Class> public> class> Main {> >// main function> >public> static> void> main(String[] argv)> >{> >// Creating Array and Populating them> >int>[] int_arr = {>1>,>2>,>3>,>4>,>5>,>6>,>7> };> >String[] str_arr> >= {>'GFG'>,>'GEEKS'>,>'GEEKSFORGEEKS'> };> > >// print integer array> >System.out.println(>'Integer Array: '> >+ Arrays.toString(int_arr));> > >// print string array> >System.out.println(>'String Array: '> >+ Arrays.toString(str_arr)> >+>'
'>);> > >// calculating the size/length of the arrays> >long> ii = Arrays.stream(int_arr).count();> >long> si = Arrays.stream(str_arr).count();> > >// print the size/length of the arrays> >System.out.println(>'Size of integer array = '> + ii);> >System.out.println(>'Size of string array = '> + si);> >}> }> |
>
>Producción
Integer Array: [1, 2, 3, 4, 5, 6, 7] String Array: [GFG, GEEKS, GEEKSFORGEEKS] Size of integer array = 7 Size of string array = 3>
La complejidad del método anterior.
Complejidad del tiempo: O(1)
Espacio Auxiliar: O(1)
Método 5: usar el método length() para verificar la longitud de la matriz Java
El longitud() método es un método de la java.lang.String clase que solo devuelve el número de caracteres de la cadena, que es una matriz de caracteres. Este método no toma ningún argumento y devuelve un En t tipo de datos.
A continuación se muestra la implementación del método anterior:
Java
// Java program to demonstrate length() method> // to calculate size/length of only char array> import> java.util.*;> > // Driver Class> public> class> Main {> >// main function> >public> static> void> main(String[] argv)> >{> >// Creating Array of character> >// and Populating them> >String char_arr =>'GEEKSFORGEEKS'>;> > >// print char array> >System.out.println(>'Char Array: '> + char_arr);> > >// calculating the size/length of the array> >int> ci = char_arr.length();> > >// print the size/length of the array> >System.out.println(>'Size of integer array = '> + ci);> >}> }> |
>
>Producción
Char Array: GEEKSFORGEEKS Size of integer array = 13>
NÓTESE BIEN.: La variable de longitud es aplicable a todos los tipos de matriz, mientras que el método length() es aplicable solo a objetos de cadena (matriz de caracteres).
Método 6: usar el método Collection size() para encontrar el tamaño de la matriz Java
El colección.tamaño() método es un método de la java.util.Colección interfaz, que es implementada por muchas clases en Java Collections Framework. Este método devuelve el número de elementos de la colección. El Recopilación La interfaz es una interfaz raíz en Java Collection Framework y está implementada por muchas clases como ArrayList, LinkedList, HashSet y TreeSet.
A continuación se muestra la implementación del método anterior:
Java
// Java program to demonstrate Collection.size() method> // to calculate size/length of array> import> java.util.Collection;> import> java.util.HashSet;> > // Driver Class> public> class> Main {> >// main function> >public> static> void> main(String[] argv)> >{> >// Creating collection> >Collection collection =>new> HashSet();> > >// Populating them> >collection.add(>1>);> >collection.add(>2>);> >collection.add(>3>);> >collection.add(>4>);> >collection.add(>5>);> >collection.add(>6>);> >collection.add(>7>);> > >// print it> >System.out.println(>'Array: '> + collection);> > >// calculating the size/length of the array> >int> ii = collection.size();> > >// print the size/length of the array> >System.out.println(>'Size of array = '> + ii);> >}> }> |
>
>Producción
Array: [1, 2, 3, 4, 5, 6, 7] Size of array = 7>
Método 7: convertir cadenas en la lista para encontrar el tamaño
El Arrays.asList(miArray).tamaño() El método se utiliza para devolver el tamaño de una matriz cuando se convierte en una Lista. El tamaño de la matriz es igual al número de elementos de la matriz.
A continuación se muestra la implementación del método anterior:
Java
// Java program to demonstrate Stream.count() method> // to calculate size/length of different arrays> > import> java.util.*;> > // Driver Class> public> class> GFG {> >// main function> >public> static> void> main(String[] argv)> >{> >// Creating String Array> >String[] str_arr> >= {>'GFG'>,>'GEEKS'>,>'GEEKSFORGEEKS'> };> > >// print string array> >System.out.println(>'String Array: '> >+ Arrays.toString(str_arr)> >+>'
'>);> > >// calculating the size/length of the array> >long> si = Arrays.asList(str_arr).size();> > >// print the size/length of the array> >System.out.println(>'Size of string array = '> + si);> >}> }> |
>
>Producción
String Array: [GFG, GEEKS, GEEKSFORGEEKS] Size of string array = 3>