This is an ordered collection (also known as a sequence). The List interface extends the Collection interface to define an ordered collection, permitting duplicates and declares the behavior of a collection that stores a sequence of elements. In addition to the operations inherited from Collection, the List interface includes it's own operations specified in below table.
The List interface is as follows:
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
// optional
E set(int index, E element);
// optional
boolean add(E element);
// optional
void add(int index, E element);
// optional
E remove(int index);
// optional
boolean addAll(int index, Collection<? extends E> c);
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view
List<E> subList(int from, int to);
Characteristics of list interface:
- The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.
- Elements can be inserted or accessed by their position in the list, using a zero-based index.
- Lists allow duplicate elements and they typically allow multiple null elements if they allow null elements at all.
- Methods of list will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.
- The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.
- The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.
Example:
package com.sample.javase.testing;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListInterfaceExample {
/**
* @param args
*/
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("servlets");
list.add("jsp");
list.add("jdbc");
// We can print list as below or we can iterate it using iterator.
System.out.println(list);
// We can access elements of listr using iterator
for (Iterator<String> iterator2 = list.iterator(); iterator2.hasNext();) {
String string = (String) iterator2.next();
System.out.println(string);
}
}
}
No comments:
Post a Comment