0% found this document useful (0 votes)
98 views

LinkedList, Jagged Array, List, and Enumeration in Java

The Java LinkedList class provides functionality of a doubly linked list data structure. Each element in a linked list is known as a node, consisting of previous, next, and data fields. The LinkedList class supports common operations like adding, accessing, modifying, and removing elements. It can also be used as a deque or queue, supporting additional methods for adding/removing elements from the front/back.

Uploaded by

Sophia Sarte
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views

LinkedList, Jagged Array, List, and Enumeration in Java

The Java LinkedList class provides functionality of a doubly linked list data structure. Each element in a linked list is known as a node, consisting of previous, next, and data fields. The LinkedList class supports common operations like adding, accessing, modifying, and removing elements. It can also be used as a deque or queue, supporting additional methods for adding/removing elements from the front/back.

Uploaded by

Sophia Sarte
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Java LinkedList

The LinkedList class of the Java collections framework provides the functionality of


the linked list data structure (doubly linkedlist).

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

Creating a Java LinkedList


Here is how we can create linked lists in Java:

LinkedList<Type> linkedList = new LinkedList<>();


Here, Type indicates the type of a linked list. For example,

// create Integer type linked list


LinkedList<Integer> linkedList = new LinkedList<>();

// create String type linked list


LinkedList<String> linkedList = new LinkedList<>();
Example: Create LinkedList in Java

import java.util.LinkedList;

class Main {
public static void main(String[] args){

// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// Add elements to LinkedList


animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);
}
}

Output

LinkedList: [Dog, Cat, Cow]

In the above example, we have created a LinkedList named animals.


Here, we have used the add() method to add elements to the LinkedList. We will learn more about
the add() method later in this tutorial.
Working of a Java LinkedList
Elements in linked lists are not stored in sequence. Instead, they are scattered and connected through
links (Prev and Next).

Here we have 3 elements in a linked list.


 Dog - it is the first element that holds null as previous address and the address of Cat as the next
address
 Cat - it is the second element that holds an address of Dog as the previous address and the address
of Cow as the next address
 Cow - it is the last element that holds the address of Cat as the previous address and null as the next
element
Methods of Java LinkedList
LinkedList provides various methods that allow us to perform different operations in linked lists. We will
look at four commonly used LinkedList Operators in this tutorial:
 Add elements
 Access elements
 Change elements
 Remove elements
1. Add elements to a LinkedList
We can use the add() method to add an element (node) at the end of the LinkedList. For example,

import java.util.LinkedList;

class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// add() method without the index parameter


animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);

// add() method with the index parameter


animals.add(1, "Horse");
System.out.println("Updated LinkedList: " + animals);
}
}

Output
LinkedList: [Dog, Cat, Cow]
Updated LinkedList: [Dog, Horse, Cat, Cow]

In the above example, we have created a LinkedList named animals. Here, we have used
the add() method to add elements to animals.
Notice the statement,

animals.add(1, "Horse");

Here, we have used the index number parameter. It is an optional parameter that specifies the position
where the new element is added.
2. Access LinkedList elements
The get() method of the LinkedList class is used to access an element from the LinkedList. For
example,

import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
// add elements in the linked list
languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
System.out.println("LinkedList: " + languages);

// get the element from the linked list


String str = languages.get(1);
System.out.print("Element at index 1: " + str);
}
}

Output
LinkedList: [Python, Java, JavaScript]
Element at index 1: Java

In the above example, we have used the get() method with parameter 1. Here, the method returns the
element at index 1.
We can also access elements of the LinkedList using the iterator() and the listIterator() method.
To learn more, visit the Java program to access elements of LinkedList.

3. Change Elements of a LinkedList


The set() method of LinkedList class is used to change elements of the LinkedList. For example,

import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in the linked list


languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java");
System.out.println("LinkedList: " + languages);

// change elements at index 3


languages.set(3, "Kotlin");
System.out.println("Updated LinkedList: " + languages);
}
}

Output
LinkedList: [Java, Python, JavaScript, Java]
Updated LinkedList: [Java, Python, JavaScript, Kotlin]

In the above example, we have created a LinkedList named languages. Notice the line,

languages.set(3, "Kotlin");

Here, the set() method changes the element at index 3 to Kotlin.


4. Remove element from a LinkedList
The remove() method of the LinkedList class is used to remove an element from the LinkedList. For
example,

import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in LinkedList


languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Kotlin");
System.out.println("LinkedList: " + languages);

// remove elements from index 1


String str = languages.remove(1);
System.out.println("Removed Element: " + str);

System.out.println("Updated LinkedList: " + languages);


}
}

Output
LinkedList: [Java, Python, JavaScript, Kotlin]
Removed Element: Python
New LinkedList: [Java, JavaScript, Kotlin]

Here, the remove() method takes the index number as the parameter. And, removes the element
specified by the index number.
Other Methods

Methods Description

contains() checks if the LinkedList contains the element

indexOf() returns the index of the first occurrence of the element

lastIndexOf() returns the index of the last occurrence of the element

clear() removes all the elements of the LinkedList

iterator() returns an iterator to iterate over LinkedList

LinkedList as Deque and Queue


Since the LinkedList class also implements the Queue and the Deque interface, it can implement
methods of these interfaces as well. Here are some of the commonly used methods:

Methods Descriptions

addFirst() adds the specified element at the beginning of the linked list

addLast() adds the specified element at the end of the linked list

getFirst() returns the first element

getLast() returns the last element

removeFirst() removes the first element

removeLast() removes the last element

peek() returns the first element (head) of the linked list

poll() returns and removes the first element from the linked list

offer() adds the specified element at the end of the linked list
Example: Java LinkedList as Queue

import java.util.LinkedList;
import java.util.Queue;

class Main {
public static void main(String[] args) {
Queue<String> languages = new LinkedList<>();

// add elements
languages.add("Python");
languages.add("Java");
languages.add("C");
System.out.println("LinkedList: " + languages);

// access the first element


String str1 = languages.peek();
System.out.println("Accessed Element: " + str1);

// access and remove the first element


String str2 = languages.poll();
System.out.println("Removed Element: " + str2);
System.out.println("LinkedList after poll(): " + languages);

// add element at the end


languages.offer("Swift");
System.out.println("LinkedList after offer(): " + languages);
}
}

Output
LinkedList: [Python, Java, C]
Accessed Element: Python
Removed Element: Python
LinkedList after poll(): [Java, C]
LinkedList after offer(): [Java, C, Swift]
Example: LinkedList as Deque

import java.util.LinkedList;
import java.util.Deque;

class Main {
public static void main(String[] args){
Deque<String> animals = new LinkedList<>();

// add element at the beginning


animals.add("Cow");
System.out.println("LinkedList: " + animals);

animals.addFirst("Dog");
System.out.println("LinkedList after addFirst(): " + animals);

// add elements at the end


animals.addLast("Zebra");
System.out.println("LinkedList after addLast(): " + animals);

// remove the first element


animals.removeFirst();
System.out.println("LinkedList after removeFirst(): " + animals);

// remove the last element


animals.removeLast();
System.out.println("LinkedList after removeLast(): " + animals);
}
}

Output
LinkedList: [Cow]
LinkedList after addFirst(): [Dog, Cow]
LinkedList after addLast(): [Dog, Cow, Zebra]
LinkedList after removeFirst(): [Cow, Zebra]
LinkedList after removeLast(): [Cow]

Iterating through LinkedList


We can use the Java for-each loop to iterate through LinkedList. For example,

import java.util.LinkedList;

class Main {
public static void main(String[] args) {
// Creating a linked list
LinkedList<String> animals = new LinkedList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("LinkedList: " + animals);

// Using forEach loop


System.out.println("Accessing linked list elements:");
for(String animal: animals) {
System.out.print(animal);
System.out.print(", ");
}
}
}

Output
LinkedList: [Cow, Cat, Dog]
Accessing linked list elements:
Cow, Cat, Dog,

LinkedList Vs. ArrayList


Both the Java ArrayList and LinkedList implements the List interface of the Collections framework.
However, there exists some difference between them.

LinkedList ArrayList

Implements List, Queue, and Deque interfaces. Implements List interface.

Stores 3 values (previous address, data, and next


Stores a single value in a single position.
address) in a single position.

Provides the doubly-linked list implementation. Provides a resizable array implementation.

Whenever an element is added, prev and next Whenever an element is added, all elements
address are changed. after that position are shifted.

To access an element, we need to iterate from the


Can randomly access elements using indexes.
beginning to the element.

https://youtu.be/M_0q6rGUsNc

https://youtu.be/YQQio9BGWgs
Jagged Array in Java
A jagged array is an array of arrays such that member arrays can be of different sizes,
i.e., we can create a 2-D array but with a variable number of columns in each row.
These types of arrays are also known as Jagged arrays. 

Pictorial representation of Jagged array in Memory:

Declaration and Initialization of Jagged array :


Syntax: data_type array_name[][] = new data_type[n][]; //n: no. of rows
array_name[] = new data_type[n1] //n1= no. of colmuns in row-1
array_name[] = new data_type[n2] //n2= no. of colmuns in row-2
array_name[] = new data_type[n3] //n3= no. of colmuns in row-3
.
.
.
array_name[] = new data_type[nk] //nk=no. of colmuns in row-n

Alternative, ways to Initialize a Jagged array :

int arr_name[][] = new int[][] {


new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

OR

int[][] arr_name = {
new int[] {10, 20, 30 ,40},
new int[] {50, 60, 70, 80, 90, 100},
new int[] {110, 120}
};

OR

int[][] arr_name = {
{10, 20, 30 ,40},
{50, 60, 70, 80, 90, 100},
{110, 120}
};
Following are Java programs to demonstrate the above concept. 

// Program to demonstrate 2-D jagged array in Java


class Main {
    public static void main(String[] args)
    {
        // Declaring 2-D array with 2 rows
        int arr[][] = new int[2][];
 
        // Making the above array Jagged
 
        // First row has 3 columns
        arr[0] = new int[3];
 
        // Second row has 2 columns
        arr[1] = new int[2];
 
        // Initializing array
        int count = 0;
        for (int i = 0; i < arr.length; i++)
            for (int j = 0; j < arr[i].length; j++)
                arr[i][j] = count++;
 
        // Displaying the values of 2D Jagged array
        System.out.println("Contents of 2D Jagged Array");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}

Output
Contents of 2D Jagged Array
0 1 2
3 4
Following is another example where i’th row has i columns, i.e., the first row has 1
element, the second row has two elements and so on.

/ Another Java program to demonstrate 2-D jagged


// array such that first row has 1 element, second
// row has two elements and so on.
class Main {
    public static void main(String[] args)
    {
        int r = 5;
 
        // Declaring 2-D array with 5 rows
        int arr[][] = new int[r][];
 
        // Creating a 2D array such that first row
        // has 1 element, second row has two
        // elements and so on.
        for (int i = 0; i < arr.length; i++)
            arr[i] = new int[i + 1];
 
        // Initializing array
        int count = 0;
        for (int i = 0; i < arr.length; i++)
            for (int j = 0; j < arr[i].length; j++)
                arr[i][j] = count++;
 
        // Displaying the values of 2D Jagged array
        System.out.println("Contents of 2D Jagged Array");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++)
                System.out.print(arr[i][j] + " ");
            System.out.println();
        }
    }
}

Output
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
Another sample program

public class Tester {


   public static void main(String[] args){
      int[][] twoDimenArray = new int[2][];

      //first row has 3 columns


      twoDimenArray[0] = new int[3];

      //second row has 4 columns


      twoDimenArray[1] = new int[4];

      int counter = 0;
      //initializing array
      for(int row=0; row < twoDimenArray.length; row++){

         for(int col=0; col < twoDimenArray[row].length; col++){


            twoDimenArray[row][col] = counter++;
         }
      }

      //printing array
      for(int row=0; row < twoDimenArray.length; row++){
         System.out.println();
         for(int col=0; col < twoDimenArray[row].length; col++){
            System.out.print(twoDimenArray[row][col] + " ");
         }
      }

   }

Output
0 1 2
3 4 5 6

The program below initializes a ragged array by assigning initial values to each row.
Here each row of the array is initialized to the column values.
class Main
{
    public static void main(String[] args)
    {
        // Declare a 2-D array with 3 rows
       int myarray[][] = new int[3][];
 
       // define and initialize jagged array
 
       myarray[0] = new int[]{1,2,3};
       myarray[1] = new int[]{4,5};
       myarray[2] = new int[]{6,7,8,9,10};
 
       // display the jagged array
       System.out.println("Two dimensional Jagged Array:");
       for (int i=0; i&lt;myarray.length; i++)
       {
          for (int j=0; j&lt;myarray[i].length; j++)
              System.out.print(myarray[i][j] + " ");
          System.out.println();
        }
    }
}
Output:

Given below is an example of a Jagged array in Java. Here the array is initialized using
for loops.
class Main {
     public static void main(String[] args)    {
        // Declaring 2-D array with 4 rows
       int intArray[][] = new int[4][];
       // create a jagged array
       intArray[0] = new int[3];
       intArray[1] = new int[2];
       intArray[2] = new int[1];
       intArray[3] = new int[4];
 
       // Initializing array with values
       for (int i=0; i&lt;intArray.length; i++)
          for(int j=0; j&lt;intArray[i].length; j++)
             intArray[i][j] = (i+1) * (j+1);         //initial values for each row,column
 
        // display the contents of 2-D jagged array
       System.out.println("Two-dimensional Jagged Array:");
       for (int i=0; i&lt;intArray.length; i++)
       {
           for (int j=0; j&lt;intArray[i].length; j++)
               System.out.print(intArray[i][j] + " ");
           System.out.println();
        }
    }
}
Output:
The above program defines a Jagged array of 4 rows. The column numbers of each row are
then defined thereby creating an array of arrays. Then using for loops that traverse both
rows and columns, the initial values are assigned to this array. The array is then printed
using for loops.

Let’s implement another example of Ragged/Jagged arrays. In this program, we create a


Jagged array in such a way that the ith row has i number of columns. This means that for
row #1 the number of column(s) will be 1, row #2 will have 2 columns, row #3 will have 3
columns and so on.

class Main {
    public static void main(String[] args)   {
        // Declare a 2-D array with 5 rows
        int intArray[][] = new int[5][];
          // create a jagged array that has i column(s) for ith row
         for (int i=0; i&lt;intArray.length; i++)
           intArray[i] = new int[i+1];
          // Initialize the jagged array
         int count = 0;
         for (int i=0; i&lt;intArray.length; i++)
            for(int j=0; j&lt;intArray[i].length; j++)
               intArray[i][j] = count++;
 
        // Display the values of 2D Jagged array
       System.out.println("A two-dimensional Jagged Array contents:");
       for (int i=0; i&lt;intArray.length; i++)
        {
           for (int j=0; j&lt;intArray[i].length; j++)
               System.out.print(intArray[i][j] + " ");
           System.out.println();
        }
    }
}
Output:

The above program output shows that each row has the number of columns equal to the
corresponding row number. The elements are initialized to a sequence starting from 0.
Java List
List in Java provides the facility to maintain the ordered collection. It contains the
index-based methods to insert, update, delete and search the elements. It can have the
duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface.
It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in
forward and backward directions. The implementation classes of List interface
are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely
used in Java programming. The Vector class is deprecated since Java 5.

List Interface declaration:


public interface List<E> extends Collection<E>  

Java List Methods

Method Description

void add(int index, E element) It is used to insert the specified element


at the specified position in a list.

boolean add(E e) It is used to append the specified


element at the end of a list.

boolean addAll(Collection<? It is used to append all of the elements


extends E> c) in the specified collection to the end of
a list.

boolean addAll(int index, It is used to append all the elements in


Collection<? extends E> c) the specified collection, starting at the
specified position of the list.

void clear() It is used to remove all of the elements


from this list.

boolean equals(Object o) It is used to compare the specified


object with the elements of a list.
int hashcode() It is used to return the hash code value
for a list.

E get(int index) It is used to fetch the element from the


particular position of the list.

boolean isEmpty() It returns true if the list is empty,


otherwise false.

int lastIndexOf(Object o) It is used to return the index in this list


of the last occurrence of the specified
element, or -1 if the list does not
contain this element.

Object[] toArray() It is used to return an array containing


all of the elements in this list in the
correct order.

<T> T[] toArray(T[] a) It is used to return an array containing


all of the elements in this list in the
correct order.

boolean contains(Object o) It returns true if the list contains the


specified element

boolean containsAll(Collection<?> It returns true if the list contains all the


c) specified element

int indexOf(Object o) It is used to return the index in this list


of the first occurrence of the specified
element, or -1 if the List does not
contain this element.

E remove(int index) It is used to remove the element


present at the specified position in the
list.
boolean remove(Object o) It is used to remove the first occurrence
of the specified element.

boolean removeAll(Collection<?> It is used to remove all the elements


c) from the list.

void replaceAll(UnaryOperator<E> It is used to replace all the elements


operator) from the list with the specified element.

void retainAll(Collection<?> c) It is used to retain all the elements in


the list that are present in the specified
collection.

E set(int index, E element) It is used to replace the specified


element in the list, present at the
specified position.

void sort(Comparator<? super E> It is used to sort the elements of the list
c) on the basis of specified comparator.

Spliterator<E> spliterator() It is used to create spliterator over the


elements in a list.

List<E> subList(int fromIndex, int It is used to fetch all the elements lies
toIndex) within the given range.

int size() It is used to return the number of


elements present in the list.

Java List vs ArrayList


List is an interface whereas ArrayList is the implementation class of List.
How to create List
The ArrayList and LinkedList classes provide the implementation of List
interface. Let's see the examples to create the List:

//Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();

//Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer>();

//Creating a List of type Book using ArrayList
List<Book> list=new ArrayList<Book>();

//Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();

In short, you can create the List of any type. The ArrayList<T> and
LinkedList<T> classes are used to specify the type. Here, T denotes the
type.

Java List Example


Let's see a simple example of List where we are using the ArrayList class as the
implementation.

import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);

}
}
Output:
Mango
Apple
Banana
Grapes

How to convert Array to List


We can convert the Array to List by traversing the array and adding the element in list one
by one using list.add() method. Let's see a simple example to convert array elements into
List.

import java.util.*;  
public class ArrayToListExample{  
public static void main(String args[]){  
//Creating Array  
String[] array={"Java","Python","PHP","C++"};  
System.out.println("Printing Array: "+Arrays.toString(array));  
//Converting Array to List  
List<String> list=new ArrayList<String>();  
for(String lang:array){  
list.add(lang);  
}  
System.out.println("Printing List: "+list);  
  
}  
}  

Output:

Printing Array: [Java, Python, PHP, C++]


Printing List: [Java, Python, PHP, C++]

How to convert List to Array


We can convert the List to Array by calling the list.toArray() method. Let's see a simple
example to convert list elements into array.

import java.util.*;  
public class ListToArrayExample{  
public static void main(String args[]){  
 List<String> fruitList = new ArrayList<>();    
 fruitList.add("Mango");    
 fruitList.add("Banana");    
 fruitList.add("Apple");    
 fruitList.add("Strawberry");    
 //Converting ArrayList to Array  
 String[] array = fruitList.toArray(new String[fruitList.size()]);    
 System.out.println("Printing Array: "+Arrays.toString(array));  
 System.out.println("Printing List: "+fruitList);  
}  
}  

Output:

Printing Array: [Mango, Banana, Apple, Strawberry]


Printing List: [Mango, Banana, Apple, Strawberry]

Get and Set Element in List


The get() method returns the element at the given index, whereas the set()
method changes or replaces the element.

import java.util.*;  
public class ListExample2{  
 public static void main(String args[]){  
 //Creating a List  
 List<String> list=new ArrayList<String>();  
 //Adding elements in the List  
 list.add("Mango");  
 list.add("Apple");  
 list.add("Banana");  
 list.add("Grapes");  
 //accessing the element    
 System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because 
index starts from 0  
 //changing the element  
 list.set(1,"Dates");  
 //Iterating the List element using for-each loop  
 for(String fruit:list)  
  System.out.println(fruit);  
  
 }  
}

Output:

Returning element: Apple


Mango
Dates
Banana
Grapes
Java ListIterator Interface
ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration

public interface ListIterator<E> extends Iterator<E>  

Methods of Java ListIterator Interface:

Method Description

void add(E e) This method inserts the specified element into the list.

boolean hasNext() This method returns true if the list iterator has more
elements while traversing the list in the forward direction.

E next() This method returns the next element in the list and
advances the cursor position.

int nextIndex() This method returns the index of the element that would
be returned by a subsequent call to next()

boolean This method returns true if this list iterator has more
hasPrevious() elements while traversing the list in the reverse direction.
E previous() This method returns the previous element in the list and
moves the cursor position backward.

E previousIndex() This method returns the index of the element that would
be returned by a subsequent call to previous().

void remove() This method removes the last element from the list that
was returned by next() or previous() methods

void set(E e) This method replaces the last element returned by next()
or previous() methods with the specified element.

Example of ListIterator Interface

import java.util.*;  
public class ListIteratorExample1{  
public static void main(String args[]){  
List<String> al=new ArrayList<String>();    
        al.add("Amit");    
        al.add("Vijay");    
        al.add("Kumar");    
        al.add(1,"Sachin");    
        ListIterator<String> itr=al.listIterator();    
        System.out.println("Traversing elements in forward direction");    
        while(itr.hasNext()){    
              
        System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());    
        }    
        System.out.println("Traversing elements in backward direction");    
        while(itr.hasPrevious()){    
          
        System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());    
        }    
}  
}  

Output:

Traversing elements in forward direction


index:0 value:Amit
index:1 value:Sachin
index:2 value:Vijay
index:3 value:Kumar
Traversing elements in backward direction
index:3 value:Kumar
index:2 value:Vijay
index:1 value:Sachin
index:0 value:Amit

Example of List: Book


Let's see an example of List where we are adding the Books.
import java.util.*;  
class Book {  
int id;  
String name,author,publisher;  
int quantity;  
public Book(int id, String name, String author, String publisher, int quantity) {  
    this.id = id;  
    this.name = name;  
    this.author = author;  
    this.publisher = publisher;  
    this.quantity = quantity;  
}  
}  
public class ListExample5 {  
public static void main(String[] args) {  
    //Creating list of Books  
    List<Book> list=new ArrayList<Book>();  
    //Creating Books  
    Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);  
    Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc Graw Hill",
4);  
    Book b3=new Book(103,"Operating System","Galvin","Wiley",6);  
    //Adding Books to list  
    list.add(b1);  
    list.add(b2);  
    list.add(b3);  
    //Traversing list  
    for(Book b:list){  
    System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);  
    }  
}  
}  

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6
Java Enumerations

Enumerations was added to Java language in JDK5. Enumeration means a list of named


constant. In Java, enumeration defines a class type. An Enumeration can have constructors,
methods and instance variables. It is created using enum keyword. Each enumeration
constant is public, static and final by default. Even though enumeration defines a class type
and have constructors, you do not instantiate an enum using new. Enumeration variables
are used and declared in much a same way as you do a primitive variable.

How to Define and Use an Enumeration

1. An enumeration can be defined simply by creating a list of enum variable. Let us


take an example for list of Subject variable, with different subjects in the list.
//Enumeration defined
enum Subject
{
Java, Cpp, C, Dbms}
2. Identifiers Java, Cpp, C and Dbms are called enumeration constants. These are
public, static and final by default.
3. Variables of Enumeration can be defined directly without any new keyword.

Example of Enumeration
Lets create an example to define an enumeration and access its constant by using
enum reference variable.
enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}

class Demo
{
public static void main(String args[])
{
WeekDays wk; //wk is an
enumeration variable of type WeekDays
wk = WeekDays.SUNDAY; //wk can be assigned only
the constants defined under enum type Weekdays
System.out.println("Today is "+wk);
}
}

Output:

Today is SUNDAY

Example of Enumeration using switch statement


Enumeration can be used in switch case to create decision making application, here we
have created an enum of restaurants that can be used to pick user choice restaurant.
enum Restaurants {
dominos, kfc, pizzahut, paninos, burgerking
}
class Test {
public static void main(String args[])
{
Restaurants r;
r = Restaurants.paninos;
switch(r) { //The name of the enumertion constants are used
without their enumeration
type name i.e only r, not Restaurants.r
case dominos: //only constants defined under enum Restaurants can
be used
System.out.println("I AM " + r.dominos);
break;
case kfc:
System.out.println("I AM " + r.kfc);
break;
case pizzahut:
System.out.println("I AM " + r.pizzahut);
break;
case paninos:
System.out.println("I AM " + r.paninos);
break;
case burgerking:
System.out.println("I AM " + r.burgerking);
break;
}
}

Output:

I AM PANINOS
Enumeration in If-Else
Enumeration can be used in if statement to compare a value with some predefined
constants. Here we are using an enumeration with if else statement.
enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}

class Demo {
public static void main(String args[])
{
WeekDays weekDays = WeekDays.WEDNESDAY;

if(weekDays == WeekDays.SUNDAY || weekDays ==


WeekDays.SATURDAY)
System.out.println("It is Weekend");
else
System.out.println("It is weekday:
"+weekDays);

}
}
Output:

It is weekday: WEDNESDAY

Traversing Enumeration Elements


We can iterate enumeration elements by calling its static method values(). This method
returns an array of all the enum constants that further can be iterate using for loop. See
the below example.

enum WeekDays{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}

class Demo {
public static void main(String args[])
{
WeekDays[] weekDays = WeekDays.values();
for(WeekDays weekday : weekDays ){

System.out.println(weekday);

}
}
}
Output:

SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Values() and ValueOf() method


All the enumerations predefined methods values() and valueOf(). values() method
returns an array of enum-type containing all the enumeration constants in it. Its general
form is,

public static enum-type[ ] values()

valueOf() method is used to return the enumeration constant whose value is equal to


the string passed in as argument while calling this method. It's general form is,

public static enum-type valueOf (String str)

Example of enumeration using values() and valueOf() methods:


Value and valueOf both are static methods of enum type and can be used to access
enum elements. Here we are using both the methods to access the enum elements.

enum Restaurants {
DOMINOS, KFC, PIZZAHUT, PANINOS, BURGERKING
}
class Demo {
public static void main(String args[])
{
Restaurants r;
System.out.println("All constants of enum type
Restaurants are:");
Restaurants rArray[] = Restaurants.values();
//returns an array of constants of type Restaurants
for(Restaurants a : rArray) //using foreach loop
System.out.println(a);

r = Restaurants.valueOf("DOMINOS");
System.out.println("It is " + r);
}
}
Output:
All constants of enum type Restaurants are:
DOMINOS
KFC
PIZZAHUT
PANINOS
BURGERKING
It is DOMINOS
Points to remember about Enumerations
1. Enumerations are of class type, and have all the capabilities that a Java class has.
2. Enumerations can have Constructors, instance Variables, methods and can even
implement Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit java.lang.Enum class.
Enumeration with Constructor, instance variable and Method
Enumeration is similar to class except it cannot be instantiated. It can have methods,
constructors, variables etc. here in this example, we are creating constructor and
method in the enum and accessing its constants value using these.
enum Student
{
John(11), Bella(10), Sam(13), Viraaj(9);
private int age; //variable defined in
enum Student
int getage() { return age; } //method defined in enum
Student
private Student(int age) //constructor defined in enum
Student
{
this.age= age;
}
}
class Demo
{
public static void main( String args[] )
{
5. Student S;
6. System.out.println("Age of Viraaj is "
+Student.Viraaj.getage()+ " years");
7. }
8. }
Output:
Age of Viraaj is 9 years

In this example as soon as we declare an enum variable(Student S), the constructor is


called once, and it initializes age for every enumeration constant with values specified with
them in parenthesis.

You might also like