About Java Array List


I summarized the learning of the collection.

This time about ArrayList </ b>.

How to use ArrayList

  • Declaration and allocation of ArrayList
ArrayList< ~ >Variable name= new ArrayList<>();

  • Specify the instance type name to be stored in ArrayList </ b> in the part of ~.

  • Add, get, delete, investigate elements

Return value Method meaning
boolean add(~) Add an element to the end of the list.
void add(int, ~) Insert the element at the int position of the list.
~ set(int, ~) Overwrite the int th element of the list.
~ get(int) Extract the int th element.
int size() Returns the number of stored elements.
~ remove(int) Delete the int th element.
  • If you use the remove () method, all the elements after the deleted element will be moved forward one by one.

Sample code


import java.util.ArrayList;  //Explanation ①

public class Main {

	public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();  //Explanation ②

		names.add("Satoshi");  //Store elements in names-It starts from 0.
		names.add("Shigeru");  // 1
		names.add("Takeshi");  // 2


		names.set(0, "Kasumi");  //0 element of names"Kasumi"Overwrite to.


		System.out.println(names.size());  //Output the number of elements

		names.remove(1);  //Delete the element at the specified position




Execution result



① Write an import statement.

(2) Use the <> symbol (generics) to specify the type to be stored.

  • important point

You cannot store anything that is not an instance. (Unable to store basic data type information.)

(Example) When storing int type information, it can be stored by converting it to a Integer </ b> instance.

(×) ArrayList<int>  (○) ArrayList<Integer>


I would like to continue to summarize the collection.

Recommended Posts