Back to: Java Tutorials For Beginners and Professionals
List Collections in Java with Examples
In this article, I am going to discuss List Collections in Java with Examples. Please read our previous article where we discussed the Java Collections Framework. As part of this article, we are going to discuss the following pointers in detail.
- List Interface in Java
- Classes of List Interface
- ArrayList Collection in Java
- LinkedList Collection in Java
- Difference Between ArrayList and LinkedList in Java
- Vector Collections in Java
- Stack Collection in Java
- Comparison Between ArrayList, LinkedList, Vector, and Stack in Java
List Interface in Java:
In Java, the List interface is an ordered collection that allows us to store and access elements sequentially. It extends the Collection interface. In Java, we must import java.util.List package in order to use List. As a List is an interface, we cannot create objects from it.
Classes of List Interface
In order to use functionalities of the List interface, we can use these classes:
- ArrayList
- LinkedList
- Vector
- Stack
These classes are defined in the Collections framework and implement the List interface.
ArrayList Collection in Java:
ArrayList is the implementation class of List Interface which is used to store a group of individual objects where duplicate values are allowed. ArrayList internally follows array structure, which means in ArrayList all the elements are stored in contiguous memory locations same as an array, but ArrayList size is not fixed.
ArrayList is not a synchronized class. If any object is synchronized we can access only one thread at a time but if an object is not. synchronized then we can access multiple threads.
Creating an ArrayList in Java
Syntax : ArrayList<Type> al = new ArrayList<Type>();
Here, Type indicates the type of ArrayList.
ArrayList Constructors in Java
ArrayList<E> al = new ArrayList<E>();
This constructor is used to create the new ArrayList with a default capacity of 10 and the size of ArrayList is 0.
ArrayList<E> al = new ArrayList<E>(int capacity);
This constructor is used to create the new ArrayList with a default capacity of 10 and the size of ArrayList is 0.
ArrayList<E> al = new ArrayList<E>(Collection obj);
This constructor is used to create the new ArrayList by copying the elements of any existing Collection (List, Set).
Points to Remember:
- size means the number of elements that are stored in Collection.
- capacity means the memory allocated for elements.
- <E> is called Generic Parameter type.
- E is the element type that must be a reference type but not any primitive type.
Methods of ArrayList: We can use all Collections Method to work with the ArrayList.
Sample Program to demonstrate ArrayList Collection in Java
import java.util.ArrayList; import java.util.List; public class ArrayListDemo { public static void main (String[]args) { // Creation of ArrayList ArrayList <Integer> al = new ArrayList <Integer>(); //adding the elements into the list al.add (10); //autoboxing al.add (new Integer (20)); //manual boxing al.add (30); al.add (40); al.add (50); //Display elements of the List and its Size System.out.println (al); System.out.println (al.size ()); //inserting an element into the List at specified location al.add (1, 77); System.out.println (al); System.out.println (al.size ()); //modifying the existing element of the List by specifying its value al.remove (new Integer (30)); System.out.println (al); System.out.println (al.size ()); //removing the element of the List by specifying its index position al.remove (0); System.out.println (al); System.out.println (al.size ()); //Displaying elements of List 1 by 1 using for loop (accessing) for (int i = 0; i < al.size (); i++) { System.out.println (al.get (i)); } //Displaying elements of List 1 by 1 using forEach Loop (auto-unboxing) for (int v:al) { System.out.println (v); } //Searching an element System.out.println (al.contains (50)); //Copying the array list into another list ArrayList < Integer > al1 = new ArrayList < Integer > (al); System.out.println (al1); } }
Output:
Note: In add(), remove(), get(), set() methods if we write any wrong index which is not available then it will throw a run time exception called IndexOutOfBoundException. ArrayList supports storing multiple null values.
ArrayList Example with Complex Data type in Java:
import java.util.*; class Customer { String name; int balance; int id; //Costructor Customer (String s, int i, int j) { name = s; balance = i; id = j; } //toString() method is overridden to give a meaningful String representaion of each object. public String toString () { return "Name : " + name + "|Balance : " + balance + "|ID : " + id; } public static void main (String args[]) { // ArrayList will contain a collection of Customer's objects. ArrayList < Customer > arr = new ArrayList < Customer > (); //Creating Customer objects. Customer customer1 = new Customer ("Jay", 1000, 2); Customer customer2 = new Customer ("Shane", 7000, 3); Customer customer3 = new Customer ("Ricky", 5000, 1); Customer customer4 = new Customer ("Tom", 3000, 6); Customer customer5 = new Customer ("Mick", 6000, 4); //Storing objects in an ArrayList collection class. arr.add (customer1); arr.add (customer2); arr.add (customer3); arr.add (customer4); arr.add (customer5); for (Customer c:arr) System.out.println (c); } }
Output:
LinkedList Collection in Java with Examples:
LinkedList is the implementation class of List Interface which is also used to store a group of individual objects where duplicate values are allowed. LinkedList internally follows a doubly linked list structure where all the elements are stored in the form of nodes that linked each other.
The LinkedList in Java is not a synchronized class. LinkedList also supports multiple null values. This provides the functionality of LinkedList Data Structure.
Each element in a linked list is known as a node. It consists of 3 fields:
- Prev – stores an address of the previous element in the list. It is null for the first element.
- Next – Stores an address of the next element in the list. It is null for the last element.
- Data – Stores the actual data
Note: Elements in linked lists are not stored in sequence. Instead, they are scattered and connected through links (Prev and Next).
Creation of LinkedList
Syntax : LinkedList<Type> ll = new LinkedList<Type>();
Here, Type indicates the type of LinkedList.
LinkedList Constructors
LinkedList<E> ll = new LinkedList<E>();
It is used to construct an Empty List.
LinkedList<E> ll = new LinkedList<E>(Collection obj);
It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator.
Note: There is no capacity concept for LinkedList.
Methods of LinkedList: We can use all Collections Method to work with the LinkedList.
Sample Program to demonstrate LinkedList Collection in Java
import java.util.*; class LinkedListDemo { public static void main (String[]args) { LinkedList < String > animals = new LinkedList <> (); // Add elements to LinkedList animals.add ("Dog"); animals.add ("Cat"); animals.add ("Horse"); System.out.println ("LinkedList: " + animals); // Get the element from the linked list String str = animals.get (1); System.out.print ("Element at index 1: " + str); System.out.println (" "); //Iterator method Iterator < String > itr = animals.iterator (); while (itr.hasNext ()) { System.out.println (itr.next ()); } } }
Output:
LinkedList Example with Complex Data type in Java:
import java.util.ArrayList; import java.util.LinkedList; class Student { String name; int age; Student(String na, int ag) { name = na; age = ag; } public String toString () { return "Name : " + name + " Age : " + age; } } public class LinkedListDemo { public static void main (String[]args) { LinkedList < Student > list1 = new LinkedList < Student > (); list1.add (new Student ("Haj", 20)); list1.add (new Student ("Raj", 19)); list1.add (new Student ("Sar", 18)); list1.add (new Student ("Kan", 17)); for (Student x:list1) { System.out.println (x); } } }
Output:
Difference Between ArrayList and LinkedList in Java:
ArrayList is slower in insertion and deletion of elements because it internally requires shifting operations, but faster in accessing the elements because ArrayList uses index position for every element.
LinkedList is faster in insertion and deletion of elements because it just requires modifying the links of nodes instead of shifting operations, but slower in accessing the elements because LinkedList does not use any index position.
Vector Collections in Java
Vector is an implemented class of List Interface. Vector class methods are by default synchronized. It is used to store a group of individual objects where duplicate values are allowed.
Vector is exactly similar to ArrayList but ArrayList is not a synchronized class where Vector is a synchronized class. Vector is also called legacy class because it is available from Java 1.0 Version. It is similar to the ArrayList, but with two differences-
- The vector is synchronized.
- Java Vector contains many legacy methods that are not part of a collections framework.
Note: It is recommended to use ArrayList in place of Vector because vectors are not thread-safe and are less efficient.
Creation of Vector
Syntax : Vector<Type> vector = new Vector<Type>();
Here, Type indicates the type of Vector.
Vector Constructors
Vector<E> v = new Vector<E>();
This constructor creates a single dimension array with a default capacity of 10.
Vector<E> v = new Vector<E>(int capacity);
This constructor sets a given capacity as a current capacity to a single dimension array.
Vector<E> v = new Vector<E>(Collection obj);
This constructor is used for migrating one collection with another collection for transferring data.
Methods of Vector
We can use all Collections Method to work with the LinkedList. We can also use legacy methods like addElement(), removeElement(), setElement(),….
Sample Program to demonstrate Vector Collection in Java
import java.util.*; class VectorDemo { public static void main(String[] args) { Vector<String> mammals= new Vector<>(); // Using the add() method mammals.add("Dog"); mammals.add("Horse"); // Using index number mammals.add(2, "Cat"); System.out.println("Vector: " + mammals); // Using addAll() Vector<String> animals = new Vector<>(); animals.add("Crocodile"); animals.addAll(mammals); System.out.println("New Vector: " + animals); // Using get() String element = animals.get(2); System.out.println("Element at index 2: " + element); // Using iterator() Iterator<String> iterate = animals.iterator(); System.out.print("Vector: "); while(iterate.hasNext()) { System.out.print(iterate.next()); System.out.print(", "); } } }
Output:
Vector Example with Complex Data type in Java
import java.util.*; class Fruits { String name; Fruits (String na) { name = na; } String getData () { return "Name : " + name; } } public class VectorDemo { public static void main (String args[]) { // create a vector with initial capacity = 2 Vector < Fruits > fruits_vec = new Vector < Fruits > (2); //add elements to the vector fruits_vec.add (new Fruits ("Grapes")); fruits_vec.add (new Fruits ("Melon")); fruits_vec.add (new Fruits ("Kiwi")); fruits_vec.add (new Fruits ("Apple")); //print current size and capacity of the vector System.out.println ("Vector Size: " + fruits_vec.size ()); System.out.println ("Default Vector capacity increment: " + fruits_vec.capacity ()); //add more elements to the vector fruits_vec.add (new Fruits ("Orange")); fruits_vec.add (new Fruits ("Mango")); fruits_vec.add (new Fruits ("Fig")); //print current size and capacity again System.out.println ("Vector Size after addition: " + fruits_vec.size ()); System.out.println ("Vector Capacity after increment: " + fruits_vec.capacity ()); } }
Output:
Stack Collection in Java:
In Java, Stack is a class that falls under the Collection framework that extends the Vector class. The stack is a child class of Vector and implements List Interface. The stack stores a group of objects by using a mechanism called LIFO. LIFE stands for Last In First Out, which means the last inserted element deleted first.
The stack data structure has the two most important operations that are push and pop. The push operation inserts an element into the stack and the pop operation removes an element from the top of the stack.
Creation of Stack
Syntax : Stack<Type> stacks = new Stack<Type>();
Here, Type indicates the Stack’s type.
Stack Constructor
public Stack()
The Stack class contains only the default constructor that creates an empty stack.
Methods of Stack
We can use all Collection Methods. We can also use legacy methods of Vector Class like addElement(), removeElement(), setelementAt(), etc. But if we want to follow the LIFO mechanism we should use Stack methods like follows:
- E push(E obj): This method will add new elements to the stack.
- E pop(): This method deletes the top element available on Stack.
- E peek(): This method just returns the top element available on Stack.
Sample Program to demonstrate Stack Collection in Java
import java.util.*; public class StackDemo { public static void main(String[] args) { Stack<Double> s = new Stack<Double>(); s.push(10.2); s.push(50.2); s.push(30.2); s.push(40.2); s.push(70.2); System.out.println(s); System.out.println(s.pop()); System.out.println(s); System.out.println(s.peek()); System.out.println(s); } }
Output:
Stack Example with Complex Data type in Java
import java.util.*; class Sports { String name; Sports (String na) { name = na; } String getData () { return "Name : " + name; } } class StackDemo { public static void main (String[]args) { Stack < Sports > stack = new Stack < Sports > (); Sports s1 = new Sports ("Cricket"); Sports s2 = new Sports ("Football"); Sports s3 = new Sports ("Basketball"); Sports s4 = new Sports ("Table Tennis"); Sports s5 = new Sports ("Badminton"); stack.push (s1); stack.push (s2); stack.push (s3); stack.push (s4); stack.push (s5); stack.pop (); stack.pop (); // Returns the number of elements present in the stack System.out.println ("Stack size is " + stack.size ()); // check if stack is empty if (stack.empty ()) System.out.println ("Stack is Empty"); else System.out.println ("Stack is not Empty"); } }
Output:
Comparison Between ArrayList, LinkedList, Vector, and Stack in Java
In the next article, I am going to discuss Cursors Collection Framework in Java with examples. Here, in this article, I try to explain List collections in Java with Examples and I hope you enjoy this List collection in Java with Examples article.