Initializing a List in Java

Java 8Object Oriented ProgrammingProgramming

The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.

Let us see an example to initialize a list in Java −

Example

 Live Demo

import java.util.*;
public class Main {
   public static void main(String[] args) {
      List list1 = new ArrayList();
      list1.add("Jacob");
      list1.add("Tom");
      list1.add("Steve");
      System.out.println(" ArrayList Elements");
      System.out.print("\t" + list1);
      List list2 = new LinkedList();
      list2.add("Jacob");
      list2.add("Tom");
      list2.add("Steve");
      System.out.println();
      System.out.println(" LinkedList Elements");
      System.out.print("\t" + list2);
   }
}

Output

ArrayList Elements
[Jacob, Tom, Steve]
LinkedList Elements
[Jacob, Tom, Steve]

Let us now see another example to initialize a list in Java −

Example

import java.util.*;
public class Main {
   public static void main(String[] args) {
      List<String> list = Arrays.asList("Tom", "Bradley", "Brad", "Steve", "David", "Katie", "Lyn");
      System.out.println("List : " + list.toString());
   }
}

Output

List : [Tom, Bradley, Brad, Steve, David, Katie, Lyn]
raja
Published on 20-Sep-2019 07:59:48
Advertisements