ArrayList<>

An array list is a pre-defined collection parameterized by the type of data it contains.

import java.util.*;

public class ArrayListDemos {

   public static void test1() {
      ArrayList<Integer> list = new ArrayList<Integer>();
      for(int i = 0; i < 10; i++) {
         list.add(i * i);
      }
      System.out.println(list);
   }

   public static void test2() {
      ArrayList<String> list = new ArrayList<String>();
      for(int i = 0; i < 10; i++) {
         list.add("String" +  i);
      }
      System.out.println(list);
   }

   public static void test3() {
      ArrayList<String> heroes = new ArrayList<String>();
      ArrayList<String> moreHeroes = new ArrayList<String>();
      heroes.add("Superman");
      heroes.add("Batman");
      heroes.add("Roidman");
      heroes.add("Spiderman");
      moreHeroes.add("Wonderwoman");
      moreHeroes.add("Catwoman");
      System.out.println(heroes);
      System.out.println(moreHeroes);
      heroes.addAll(moreHeroes);
      System.out.println(heroes);
      heroes.remove("Roidman");
      System.out.println(heroes);
      heroes.set(2, "Dark Knight");
      System.out.println(heroes);
      for(int i = 0; i < heroes.size(); i++) {
         System.out.println(heroes.get(i));
      }

   }


   public static void main(String[] args) {
      test1();
      test2();
      test3();
   }


}

Program Output

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[String0, String1, String2, String3, String4, String5, String6, String7, String8, String9]
[Superman, Batman, Roidman, Spiderman]
[Wonderwoman, Catwoman]
[Superman, Batman, Roidman, Spiderman, Wonderwoman, Catwoman]
[Superman, Batman, Spiderman, Wonderwoman, Catwoman]
[Superman, Batman, Dark Knight, Wonderwoman, Catwoman]
Superman
Batman
Dark Knight
Wonderwoman
Catwoman

The Enhanced For-Loop

The enhanced for loop is the cool way to traverse an array list. Here's the general form:

for(ElementType var: someList) {
   // in here var will take on every value in someList
}

For example:

ArrayList<String> heroes = new ArrayList<String>();
heroes.add("Superman");
heroes.add("Batman");
heroes.add("Spiderman");
heroes.add("Wonderwoman");
heroes.add("Catwoman");

for(String hero: heroes) {
   System.out.println("Hero: " + hero);
}