how to create Java ArrayList

how to create Java ArrayList

An ArrayList is a resizable-array implementation of the List interface in Java. To create an ArrayList, you can use the following syntax:

refer t‮tual:o‬turi.com
import java.util.ArrayList;

ArrayList<Type> list = new ArrayList<Type>();

Here, Type is the type of elements that the ArrayList will store. For example, to create an ArrayList of integers, you can use the following code:

import java.util.ArrayList;

ArrayList<Integer> list = new ArrayList<Integer>();

You can also create an ArrayList with a specified initial capacity using the following syntax:

import java.util.ArrayList;

ArrayList<Type> list = new ArrayList<Type>(capacity);

For example, to create an ArrayList of strings with an initial capacity of 10, you can use the following code:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<String>(10);

Note: Since Java 7, you can use the diamond operator (<>) to infer the type of the elements in the ArrayList from the context. Therefore, the following syntax is also valid:

import java.util.ArrayList;

ArrayList<Type> list = new ArrayList<>();

For example:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();

You can then add elements to the ArrayList using the add method:

list.add(element);

For example:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

You can also use the addAll method to add all the elements from another collection to the ArrayList:

list.addAll(anotherCollection);

For example:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");

ArrayList<String> anotherList = new ArrayList<>();
anotherList.add("mango");
anotherList.add("orange");

list.addAll(anotherList);

This will add the elements "mango" and "orange" to the end of the listArrayList.

You can access the elements of the ArrayList using the get method:

Type element = list.get(index);

Here, index is the index of the element that you want to retrieve. The index of the first element is 0, the index of the second element is 1, and so on.

For example:

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
Created Time:2017-11-01 20:42:48  Author:lautturi