¿Cómo declaro e inicializo un array en Java?


¿Cómo declaro e inicializo un array en Java?

Author: Peter Mortensen, 2009-07-29

19 answers

Puede usar declaración de matriz o literal de matriz (pero solo cuando declara y afecta la variable de inmediato, los literales de matriz no se pueden usar para reasignar una matriz).

Para tipos primitivos:

int[] myIntArray = new int[3];
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};

Para las clases, por ejemplo String, es lo mismo:

String[] myStringArray = new String[3];
String[] myStringArray = {"a","b","c"};
String[] myStringArray = new String[]{"a","b","c"};

La tercera forma de inicializar es útil cuando se declara el array primero y luego se inicializa. El reparto es necesario aquí.

String[] myStringArray;
myStringArray = new String[]{"a","b","c"};
 2251
Author: glmxndr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-16 02:37:29

Hay dos tipos de matriz.

Matriz unidimensional

Sintaxis para los valores por defecto:

int[] num = new int[5];

O (menos preferido)

int num[] = new int[5];

Sintaxis con valores dados (inicialización de variable/campo):

int[] num = {1,2,3,4,5};

O (menos preferido)

int num[] = {1, 2, 3, 4, 5};

Nota: Por conveniencia int [] num es preferible porque dice claramente que usted está hablando aquí de matriz. De lo contrario, no hay diferencia. Para nada.

Multidimensional array

Declaración

int[][] num = new int[5][2];

O

int num[][] = new int[5][2];

O

int[] num[] = new int[5][2];

Inicialización

 num[0][0]=1;
 num[0][1]=2;
 num[1][0]=1;
 num[1][1]=2;
 num[2][0]=1;
 num[2][1]=2;
 num[3][0]=1;
 num[3][1]=2;
 num[4][0]=1;
 num[4][1]=2;

O

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

Matriz irregular (o Matriz no rectangular)

 int[][] num = new int[5][];
 num[0] = new int[1];
 num[1] = new int[5];
 num[2] = new int[2];
 num[3] = new int[3];

Así que aquí estamos definiendo columnas explícitamente.
Otra manera:

int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };

Para Acceder:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}

Alternativamente:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}

Los arrays irregulares son arrays multidimensionales.
Para una explicación ver detalle de matriz multidimensional en el tutoriales oficiales de java

 226
Author: Isabella Engineer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-20 20:57:10
Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};

También es válido, pero prefiero los corchetes después del tipo, porque es más fácil ver que el tipo de la variable es en realidad una matriz.

 117
Author: Nate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-12 19:48:12

Hay varias formas en las que puede declarar un array en Java:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};

Puedes encontrar más información en el sitio Sun tutorial y en el JavaDoc.

 32
Author: Anirudh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 17:14:48

Me parece útil si entiendes cada parte:

Type[] name = new Type[5];

Type[] es el tipo de la variable llamada name ("name" se llama el identificador ). El literal "Type" es el tipo base, y los corchetes significan que este es el tipo de matriz de esa base. Los tipos de matriz son a su vez tipos propios, lo que le permite hacer matrices multidimensionales como Type[][] (el tipo de matriz de Type[]). La palabra clave new dice asignar memoria para la nueva matriz. El número entre el soporte dice cuán grande será la nueva matriz y cuánta memoria asignar. Por ejemplo, si Java sabe que el tipo base Type toma 32 bytes, y desea una matriz de tamaño 5, necesita asignar internamente 32 * 5 = 160 bytes.

También puede crear matrices con los valores ya existentes, como

int[] name = {1, 2, 3, 4, 5};

Que no solo crea el espacio vacío sino que lo llena con esos valores. Java puede decir que las primitivas son enteros y que hay 5 de ellos, por lo que el tamaño de la la matriz se puede determinar implícitamente.

 26
Author: Chet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-12 09:45:24

Lo siguiente muestra la declaración de un array, pero el array no está inicializado:

 int[] myIntArray = new int[3];

Lo siguiente muestra la declaración así como la inicialización del array:

int[] myIntArray = {1,2,3};

Ahora, lo siguiente también muestra la declaración, así como la inicialización de la matriz:

int[] myIntArray = new int[]{1,2,3};

Pero esta tercera muestra la propiedad de la creación de objetos de matriz anónima que está apuntada por una variable de referencia "myIntArray", por lo que si escribimos solo "new int [] {1,2,3};" entonces esto es cómo se puede crear un objeto de matriz anónimo.

Si solo escribimos:

int[] myIntArray;

Esto no es una declaración de array, pero la siguiente declaración completa la declaración anterior:

myIntArray=new int[3];
 26
Author: Amit Bhandari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-22 21:57:37

Alternativamente,

// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];

Que declara un array llamado arrayName de tamaño 10 (tiene elementos del 0 al 9 para usar).

 22
Author: Thomas Owens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-29 14:25:31

También, en caso de que desee algo más dinámico, está la interfaz de Lista. Esto no funcionará tan bien, pero es más flexible:

List<String> listOfString = new ArrayList<String>();

listOfString.add("foo");
listOfString.add("bar");

String value = listOfString.get(0);
assertEquals( value, "foo" );
 22
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-19 10:41:04

Hay dos formas principales de hacer un array:

Este, para una matriz vacía:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array

Y este, para una matriz inicializada:

int[] array = {1,2,3,4 ...};

También puede hacer arreglos multidimensionales, como este:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
 12
Author: codecubed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-25 22:00:15

Tomar el tipo primitivo int, por ejemplo. Hay varias formas de declarar y int array:

int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};

Donde en todos estos, puedes usar int i[] en lugar de int[] i.

Con la reflexión, se puede utilizar (Type[]) Array.newInstance(Type.class, capacity);

Tenga en cuenta que en los parámetros del método, ... indica variable arguments. Esencialmente, cualquier número de parámetros está bien. Es más fácil de explicar con código:

public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};

Dentro del método, varargs se trata como un int[] normal. Type... solo se puede usar en el método parámetros, por lo que int... i = new int[] {} no compilará.

Tenga en cuenta que al pasar un int[] a un método (o cualquier otro Type[]), no puede usar la tercera vía. En la sentencia int[] i = *{a, b, c, d, etc}*, el compilador asume que el {...} significa un int[]. Pero eso es porque estás declarando una variable. Al pasar una matriz a un método, la declaración debe ser new Type[capacity] o new Type[] {...}.

Arreglos multidimensionales

Los arrays multidimensionales son mucho más difíciles de tratar. Esencialmente, una matriz 2D es un matriz de matrices. int[][]significa una matriz de int[] s. La clave es que si un int[][] se declara como int[x][y], el índice máximo es i[x-1][y-1]. Esencialmente, un int[3][5] rectangular es:

[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]
 9
Author: HyperNeutrino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-23 20:09:02

Si desea crear matrices utilizando reflexiones, puede hacer lo siguiente:

 int size = 3;
 int[] intArray = (int[]) Array.newInstance(int.class, size ); 
 7
Author: Muhammad Suleman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-23 20:08:00

Declarando una matriz de referencias de objetos:

class Animal {}

class Horse extends Animal {
    public static void main(String[] args) {

        /*
         * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
         */
        Animal[] a1 = new Animal[10];
        a1[0] = new Animal();
        a1[1] = new Horse();

        /*
         * Array of Animal can hold Animal and Horse and all subtype of Horse
         */
        Animal[] a2 = new Horse[10];
        a2[0] = new Animal();
        a2[1] = new Horse();

        /*
         * Array of Horse can hold only Horse and its subtype (if any) and not
           allowed supertype of Horse nor other subtype of Animal.
         */
        Horse[] h1 = new Horse[10];
        h1[0] = new Animal(); // Not allowed
        h1[1] = new Horse();

        /*
         * This can not be declared.
         */
        Horse[] h2 = new Animal[10]; // Not allowed
    }
}
 7
Author: ravi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-25 21:59:45

Array es una lista secuencial de elementos

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

Si es un objeto, entonces es el mismo concepto

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

En el caso de los objetos, es necesario asignar a null para inicializar usando new Type(..), clases como String y Integer son casos especiales que se manejan de la siguiente

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

En general, puede crear matrices que sean M dimensionales

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

Vale la pena señalar que crear una matriz dimensional M es caro en términos de Espacio. Ya cuando se crea una matriz dimensional M con N en todas las dimensiones, el tamaño total de la matriz es mayor que N^M, ya que cada matriz tiene una referencia, y en la dimensión M hay una matriz dimensional (M-1) de referencias. El tamaño total es el siguiente

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data
 6
Author: Khaled.K,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-21 13:45:04

Para crear matrices de objetos de clase puede usar el java.util.ArrayList. para definir un array:

public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();

Asigne valores a la matriz:

arrayName.add(new ClassName(class parameters go here);

Leer del array:

ClassName variableName = arrayName.get(index);

Nota:

variableName es una referencia al array que significa que manipular {[6] } manipulará arrayName

Para bucles:

//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName

Bucle For que permite editar arrayName (bucle for convencional):

for (int i = 0; i < arrayName.size(); i++){
    //manipulate array here
}
 5
Author: Samuel Newport,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-08 10:10:35

En Java 8 se puede usar así.

String[] strs = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> Integer.toString(i))
    .toArray(String[]::new);
 5
Author: Chamly Idunil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-08 18:21:39

En Java 9

El Uso de diferentes IntStream.iterate y IntStream.takeWhile métodos:

int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();

Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]


int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();

Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

En Java 10

Usando la Inferencia de Tipo de Variable Local :

var letters = new String[]{"A", "B", "C"};
 4
Author: Oleksandr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-15 21:48:56

Declare e inicialice para Java 8 y versiones posteriores. Crear un array entero simple:

int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Crear una matriz aleatoria para enteros entre [-50, 50] y para dobles [0 ,1E17]:

int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();

Secuencia de potencia de dos:

double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]

Para String [] debe especificar un constructor:

String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));

Arreglos multidimensionales:

String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
    .toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
 3
Author: Kirill Podlivaev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 22:36:26

Otra forma de declarar e inicializar ArrayList:

private List<String> list = new ArrayList<String>(){{
    add("e1");
    add("e2");
}};
 1
Author: Clement.Xu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-04 07:42:26
int[] SingleDimensionalArray = new int[2]

int[][] MultiDimensionalArray = new int[3][4]
 -6
Author: TreyMcGowan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-19 20:01:59