Java is an object-oriented programming language that is widely used for developing applications.
A list is a data structure in Java that is used to store elements in a specific order.
In this article, we will learn how to initialize a List object in Java.
Different Ways to Initialize a List Object in Java
There are several ways to initialize a List object in Java, and they are as follows:
Using the ArrayList class
The ArrayList class is a part of the Java Collection framework and is used to store a collection of elements in a dynamic array. Here is an example of how to initialize an ArrayList object:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("Java"); list.add("Python"); list.add("C++"); System.out.println(list); } }
Using the LinkedList class
The LinkedList class is a part of the Java Collection framework and is used to store a collection of elements in a linked list.
Here is an example of how to initialize a LinkedList object:
import java.util.LinkedList; public class Main { public static void main(String[] args) { LinkedList list = new LinkedList(); list.add("Java"); list.add("Python"); list.add("C++"); System.out.println(list); } }
Using Arrays.asList() method
The Arrays.asList() method is used to initialize a List object from an array of elements.
Here is an example of how to use this method:
import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List list = Arrays.asList("Java", "Python", "C++"); System.out.println(list); } }
Conclusion
In this article, we learned how to initialize a List object in Java.
We looked at three different ways to initialize a List object, using the ArrayList class, the LinkedList class, and the Arrays.asList() method.
I hope you found this article helpful and that you now have a better understanding of how to initialize a List object in Java.