LinkedList, Jagged Array, List, and Enumeration in Java
LinkedList, Jagged Array, List, and Enumeration in Java
import java.util.LinkedList;
class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
Output
import java.util.LinkedList;
class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
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);
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.
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
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");
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
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
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
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);
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<>();
animals.addFirst("Dog");
System.out.println("LinkedList after addFirst(): " + animals);
Output
LinkedList: [Cow]
LinkedList after addFirst(): [Dog, Cow]
LinkedList after addLast(): [Dog, Cow, Zebra]
LinkedList after removeFirst(): [Cow, Zebra]
LinkedList after removeLast(): [Cow]
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);
Output
LinkedList: [Cow, Cat, Dog]
Accessing linked list elements:
Cow, Cat, Dog,
LinkedList ArrayList
Whenever an element is added, prev and next Whenever an element is added, all elements
address are changed. after that position are shifted.
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.
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.
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.
Output
Contents of 2D Jagged Array
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
Another sample program
int counter = 0;
//initializing array
for(int row=0; row < twoDimenArray.length; row++){
//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<myarray.length; i++)
{
for (int j=0; j<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<intArray.length; i++)
for(int j=0; j<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<intArray.length; i++)
{
for (int j=0; j<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.
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<intArray.length; i++)
intArray[i] = new int[i+1];
// Initialize the jagged array
int count = 0;
for (int i=0; i<intArray.length; i++)
for(int j=0; j<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<intArray.length; i++)
{
for (int j=0; j<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.
Method Description
void sort(Comparator<? super E> It is used to sort the elements of the list
c) on the basis of specified comparator.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies
toIndex) within the given range.
//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.
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
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:
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:
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:
public interface ListIterator<E> extends Iterator<E>
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.
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:
Output:
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
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;
}
}
Output:
It is weekday: WEDNESDAY
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
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