Lecture Videos
  1  import java.util.ArrayList;
  2  
  3  public class TestArrayList {
  4    public static void main(String[] args) {
  5      // Create a list to store cities
  6      ArrayList<String> cityList = new ArrayList<>();
  7  
  8      // Add some cities in the list
  9      cityList.add("London");
 10      // cityList now contains [London]
 11      cityList.add("Denver");
 12      // cityList now contains [London, Denver]
 13      cityList.add("Paris");
 14      // cityList now contains [London, Denver, Paris]
 15      cityList.add("Miami");
 16      // cityList now contains [London, Denver, Paris, Miami]
 17      cityList.add("Seoul");
 18      // contains [London, Denver, Paris, Miami, Seoul]
 19      cityList.add("Tokyo");
 20      // contains [London, Denver, Paris, Miami, Seoul, Tokyo]
 21  
 22      System.out.println("List size? " + cityList.size()); 
 23      System.out.println("Is Miami in the list? " +
 24        cityList.contains("Miami")); 
 25      System.out.println("The location of Denver in the list? "
 26        + cityList.indexOf("Denver")); 
 27      System.out.println("Is the list empty? " +
 28        cityList.isEmpty()); // Print false
 29  
 30      // Insert a new city at index 2
 31      cityList.add(2, "Xian");
 32      // contains [London, Denver, Xian, Paris, Miami, Seoul, Tokyo]
 33  
 34      // Remove a city from the list
 35      cityList.remove("Miami");
 36      // contains [London, Denver, Xian, Paris, Seoul, Tokyo]
 37  
 38      // Remove a city at index 1
 39      cityList.remove(1);
 40      // contains [London, Xian, Paris, Seoul, Tokyo]
 41  
 42      // Display the contents in the list
 43      System.out.println(cityList.toString());
 44  
 45      // Display the contents in the list in reverse order
 46      for (int i = cityList.size() - 1; i >= 0; i--)
 47        System.out.print(cityList.get(i) + " ");
 48      System.out.println();
 49      
 50      // Create a list to store two circles
 51      ArrayList<Circle> list = new ArrayList<>();
 52      
 53      // Add two circles
 54      list.add(new Circle(2));
 55      list.add(new Circle(3));
 56      
 57      // Display the area of the first circle in the list
 58      System.out.println("The area of the circle? " +
 59        list.get(0).getArea());
 60    }
 61  }