ArrayList

Source

  • ArrayList is a resizable array. The size of an array cannot be modified.
  • You cannot add/remove elements from an array, but this is possible with an ArrayList.
// initiating an ArrayList

import java.util.ArrayList; //import ArrayList class

List<String> listings = new ArrayList<String>(); // a List is an interface, and an ArrayList is an instance of the List interface

ArrayList Methods

import java.util.ArrayList;

List<String> clothes = new ArrayList<String>();
List<String> objects = new ArrayList<String>();
List<String> listings = new ArrayList<String>();

clothes.add("pe shirt"); // add "pe shirt" to clothes arraylist
clothes.add("used prom dress");
clothes.add("shoes");
objects.add("pe lock"); // add "pe lock" to objects arraylist

listings.addAll(clothes);
listings.addAll(objects); // add objects and clothes arrays to listings

System.out.println(listings); // listings has content from both clothes and objects
[pe shirt, used prom dress, shoes, pe lock]
// get first element of the listings ArrayList
listings.get(0);
System.out.println("original first element: " + listings.get(0));

// change first element of the listing ArrayList
listings.set(0, "black jeans");
System.out.println("new first element: " + listings.get(0));

// remove elements from array
System.out.println("original arraylist: " + listings);
listings.remove(0);
System.out.println("first element remove: " + listings);
listings.clear();
System.out.println("cleared arraylist: " + listings);
original first element: black jeans
new first element: black jeans
original arraylist: [black jeans, used prom dress, shoes, pe lock]
first element remove: [used prom dress, shoes, pe lock]
cleared arraylist: []