It is the fundamental concept of java collections framework. Main purpose of this concept is to traverse the list and its objects.
‘List interface’ – it deals with ordered sequence of
elements. If you want to extend this interface for additional methods, just use
the ‘Collection’ interface.
Collection interface has many methods for searching,
traversing, viewing and particular position access.
Features:
- · It supports null elements.
- · It deals with ordered collection.
- · Duplicates can be included.
- · Mainly, a particular position is easily accessed.
How to implement the “List Interface”?
To implement the list
interface, you can use any of the data structure given below.
- · Stack
- · Vector
- · Linked list
- · ArrayList
A simple implementation of list interface using Array List and
linked list is given below.
Steps to follow:
- First create a class with main() function.
- It has two parts. One is using an arrayList and another one is using linkedlist.
arrayList:
- · An arraylist object is created. 3 data elements are added to arrayList.
- · The array list is printed using the object.
Linkedlist:
- · A new object is created and three elements are added. Finally,it was displayed using a linked list.
Program:
import java.util.*;
public class ListSample {
public static void main(String[] args) {
List<String> arrayList1 = new
ArrayList<>();
arrayList1.add("Cow");
arrayList1.add("Goat");
arrayList1.add("Sheep");
System.out.println("The form
animal ArrayList is: " + arrayList1);
List<String> linkedList1 = new
LinkedList<>();
linkedList1.add("Lion");
linkedList1.add("Tiger");
linkedList1.add("Fox");
System.out.println("The wild
animal LinkedList is: " + linkedList1);
}
}
The output is given below.
C:\raji\blog>javac ListSample.java
C:\raji\blog>java ListSample
The form animal ArrayList is: [Cow, Goat, Sheep]
The wild animal LinkedList is: [Lion, Tiger, Fox]
This is the basic implementation of list interface. Next, the
way of doing the iteration is given below.
The iteraton:
It includes
the traversal on list interface. It has many methods listed below.
- · next() – it gives you the next element.
- · hasNext() – it gives you whether next element is available or not.
- · remove() -it deletes an data.
Program uses these three methods:
import java.util.*;
public class IteratorEg {
public static void
main(String[] args) {
List<String> list2 = new ArrayList<>();
list2.add("alpha");
list2.add("beta");
list2.add("gamma");
Iterator<String> iterator1 = list2.iterator();
while
(iterator1.hasNext()) {
String
data = iterator1.next();
System.out.println(data);
if
(data.equals("beta")) {
iterator1.remove();
}
}
System.out.println("Here is the list after iteration: " +
list2);
}
}
Output:
C:\raji\blog>javac IteratorEg.java
C:\raji\blog>java IteratorEg
alpha
beta
gamma
Here is the list after iteration: [alpha, gamma]
These are the ways to use the iterators in list interface.Happy
coding!!!!
No comments:
Post a Comment