En este programa, vamos a aprender crear un ArrayList, la adición de elementos al índice específico e imprimirlas en la pantalla de salida .
En este programa, estamos añadiendo 5 elementos (100, 200, 300, 400 y 500) a la ArrayList usando “add ()” método de ArrayList class.
Además , estamos añadiendo dos elementos más que son tipo de cadena; Aquí vamos a añadir “Hola” en el índice 1 , “mundo” en el índice 2 y “Hola” en el índice 4 .
Sintaxis de ArrayList.add () método
ArrayList.add(index, element);
Aquí,
- índice – es el índice del elemento, donde tenemos que añadir un elemento
- elemento – es el elemento (elemento), que tiene que ser añadido
Considere el programa
import java.util.ArrayList;
public class ExArrayList {
public static void main(String[] args) {
////Creating object of ArrayList
ArrayList arrList = new ArrayList();
//adding data to the list
arrList.add("100");
arrList.add("200");
arrList.add("300");
arrList.add("400");
arrList.add("500");
//ading data to specified index in array list
//we are adding "Hello" at index 1, "World" at index 2 and "Hi there" at index 4
arrList.add(1,"Hello");
arrList.add(2,"World");
arrList.add(4,"Hi there");
System.out.println("Array List elements: ");
//display elements of ArrayList
for(int iLoop=0; iLoop < arrList.size(); iLoop++)
System.out.println(arrList.get(iLoop));
}
}
salida
Array List elements:
100
Hello
World
200
Hi there
300
400
500