June 21

0  comments

What is List interface?


The List interface extends Collection Interface. It has the following features.

  • A List is always an ordered collection
  • List can hold duplicate elements.
  • Since List is an ordered collection, insertion and deletion of element based on position is possible.

We will see these natures of a List in an upcoming example.

Which classes implement List interface directly and indirectly?


The AbstractList class implements List interface. ArrayList, AbstractSequentialList and Vector classes extend AbstractList.

LinkedList extends AbstractSequentialList, which implements Deque interface as well.

Refer to Collection Framework hierarchy diagram for more details. 

Demonstrate the features of List using a program.

 
Since List is an interface, we cannot directly create object of List, we must use implementing class to do so. We will use ArrayList for this purpose.

import java.util.*;

public class ListDemo {
public static void main(String[] args)
{
// Creating a list
List<Integer> l1
= new ArrayList<Integer>();

// Adds 1 at 0 index
l1.add(0, 1);

// Adds 2 at 1 index
l1.add(1, 2);
System.out.println(l1);

// Creating another list
List<Integer> l2
= new ArrayList<Integer>();

l2.add(1);
l2.add(2);
l2.add(3);

// Will add list l2 from 1 index
l1.addAll(1, l2);
System.out.println(l1);

// Removes element from index 1
l1.remove(1);
System.out.println(l1);

// Prints element at index 3
System.out.println(l1.get(3));

// Replace 0th element with 5
l1.set(0, 5);
System.out.println(l1);
}
}


Output:

[1, 2]
[1, 1, 2, 3, 2]
[1, 2, 3, 2]
2
[5, 2, 3, 2]

Explanation

In the above program, we have shown how to create a list, how to add elements to the list, how to get the index of a particular element in a list, how to replace an element in each index of a list.


What are the different ways to iterate over a List?


We can iterate a List using for each loop, Iterator or a ListIterator. The first 2 options have been discussed earlier, so we will see how we can use ListIterator to iterate over a List.

ListIterator is an interface in java.util package and extends Iterator interface. ListIterator is exclusively used to iterate a List, not other collection types.

Example

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorExample {
public static void main(String a[]){
ListIterator<String> litr = null;
List<String> names = new ArrayList<String>();
names.add("Shyam");
names.add("Rajat");
names.add("Paul");
names.add("Tom");
names.add("Kate");
//Obtaining list iterator
litr=names.listIterator();

System.out.println("Traversing the list in forward direction:");
while(litr.hasNext()){
System.out.println(litr.next());
}
System.out.println("\nTraversing the list in backward direction:");
while(litr.hasPrevious()){
System.out.println(litr.previous());
}
}
}
Output:
Traversing the list in forward direction:
Shyam
Rajat
Paul
Tom
Kate

Traversing the list in backward direction:
Kate
Tom
Paul
Rajat
Shyam

What are the differences between Iterator & ListIterator?
What is LinkedList and what are the differences between LinkedList & ArrayList?

LinkedList is another implementation of List interface, so all features a List has, LinkedList inherits those by default.

Based on the table below, we should be able to decide when to use ArrayList and when to use LinkedList to create a List type collection.

What is singly and doubly linked list? What are the differences between them?

Singly Linked List

A singly linked list is a list that consists of a collection of nodes, and each node has two parts; one part is the data part, and another part is the address. Let us have a look at the diagram below which is of a Singly Linked List.


There are 4 nodes in this LinkedList. The address of the first node is 100, which the head pointer holds. The value of the first node (which is the first data also in the LinkedList collection) is 10. The first node also holds the address of the second node, which is 200. The value of the second node is 20. This chain continues until it reaches the last node.

Doubly Linked List

A doubly linked list is another type of the linked list. It is called a doubly linked list because it contains two addresses while a singly linked list contains a single address. It is a list that has total three parts, one is a data part, and others two are the pointers, i.e., previous, and next.

The previous pointer holds the address of the previous node, and the next pointer holds the address of the next node. Therefore, we can say that list has two references, i.e., forward, and backward reference to traverse in either direction.


The first node has a previous pointer of NULL since before the first node, there is no node. Similarly, the last node has a next address as NULL.

Here are the differences of Singly vs Doubly Linked List.

How to print elements of a LinkedList in reverse order?

import java.util.*;
public class LinkedList4{
public static void main(String args[]){

LinkedList<String> list=new LinkedList<String>();
list.add("Tom");
list.add("Sam");
list.add("Ron");
//Traversing the list of elements in reverse order
Iterator i= list.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}

}
}

Output:

Ron
Sam
Tom


The descendingIterator() method of Iterator interface is used to fetch the elements in a reversed order.

How do we sort a List in ascending and descending order?

We can sort a List in ascending and descending order by using sort() method of Collections class.

Example –

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Main {

public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(101);
list.add(501);
list.add(98);
list.add(201);
System.out.println("In ascending Order");
Collections.sort(list);
Iterator itr1 = list.iterator();
while (itr1.hasNext()) {
System.out.println(itr1.next());
}

System.out.println("In descending Order");
Collections.sort(list, Collections.reverseOrder());
Iterator itr2 = list.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}

Output

In ascending Order
98
101
201
501
In descending Order
501
201
101
98

How to convert an array to an ArrayList and vice versa?

Example1 –

import java.util.ArrayList;

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

// Add elements in the arraylist
games.add("Soccer");
games.add("Cricket");
games.add("Hockey");
System.out.println("ArrayList: " + games);

// Create a new array of String type
String[] arr = new String[games.size()];

// Convert ArrayList into the string array
games.toArray(arr);
System.out.print("Array: ");
for(String item:arr) {
System.out.print(item+", ");
}
}
}

Output

ArrayList: [Soccer, Cricket, Hockey]
Array: Soccer, Cricket, Hockey

Explanation

In the above example, we have created an arraylist named games. Using toArray() method we are converting the ArrayList to an array.

Example2 –

import java.util.Arrays;
import java.util.ArrayList;

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

// create an array
String[] arr = {"India", "Australia", "Canada"};
System.out.println("Array: " + Arrays.toString(arr));

// convert array to arraylist
ArrayList<String> countries= new ArrayList<>(Arrays.asList(arr));

System.out.println("ArrayList: " + countries);

}
}

Output

Array: [India, Australia, Canada]
ArrayList: [India, Australia, Canada]

Explanation

We can convert an array to an ArrayList using asList() method of Arrays class.


Tags


You may also like

Groups attribute in TestNG 

Groups attribute in TestNG 
Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}