• List is an interface, and the instances of List can be created by implementing various classes.
  • ArrayList class is used to create a dynamic array that contains objects.

Travel Places Example

  • place.add
  • place.remove
  • place.get()
  • place.size()
  • place.set()
// Main class
public class places {
   
    // Main driver method
    public static void main()
    {
        // Creating an object of List class
          // Declaring an object of String type with
        // reference to ArrayList class
        // Type safe list 
        ArrayList<String> place = new ArrayList<String>(); //place - object, <String> - type
       
        // Adding elements using add() method
        // Custom input elements
        place.add("New York");
        place.add("Hawii");
        place.add("Los Angeles");
        place.add("Korea");
 
        // Print and display the elements in
        // ArrayList class object 
        System.out.println("a list of places to travel: " + place);

        //remove element of index 1
        place.remove(1); 
        System.out.println("a lists of places to travel after traveled to Hawii: " + place);

        //print index 1 of the arraylist with Hawii removed
        System.out.println("where do you want to travel to next? " + place.get(1)); //new index 1 is Los Angeles

        //print the size of the arraylist 
        System.out.println("numbers of places that you are going to travel to: " + place.size()); 

        //change index 1 to Japan
        place.set(1, "Japan");
        System.out.println("changing Los Angeles to Japan: " + place);

    }
}

places.main();
a list of places to travel: [New York, Hawii, Los Angeles, Korea]
a lists of places to travel after traveled to Hawii: [New York, Los Angeles, Korea]
where do you want to travel to next? Los Angeles
numbers of places that you are going to travel to: 3
changing Los Angeles to Japan: [New York, Japan, Korea]

Two ArrayLists (< String > < Integer >)

import java.util.*;

public class places<T> {

    public static void main()
    {
        // arraylist <String>
        ArrayList<String> place = new ArrayList<String>(); //place - object, <String> - type
       
        place.add("New York");
        place.add("Hawii");
        place.add("Los Angeles");
        place.add("Korea");
 
        System.out.println("a list of places to travel: " + place);

        
        // new arraylist <Integer>
        ArrayList<Integer> placeNumber = new ArrayList<Integer>();

        placeNumber.add(30);
        placeNumber.add(14);
        placeNumber.add(3);

        System.out.println("how many possible days do you want to travel for: " + placeNumber);
        System.out.println("how many days you plan to stay in Korea for: " + placeNumber.get(1));


    }
}

places.main();
a list of places to travel: [New York, Hawii, Los Angeles, Korea]
how many possible days do you want to travel for: [30, 14, 3]
how many days you plan to stay in Korea for: 14