Showing posts with label list-interface. Show all posts
Showing posts with label list-interface. Show all posts

Thursday, May 19, 2011

Operations on Lists in java

Creating a list:

List listA = new ArrayList();



Adding Elements


To add elements to a List you call its add() method. This method is inherited from the Collection interface. Here are a few examples:

listA.add("element 1");
listA.add("element 2");
listA.add("element 3");


Adding element at particular index, like index 0 here:


listA.add(0, "element 0");


Accessing elements:


This is done by get method, which gets the element from particular index:


String element0 = listA.get(0);


Removing elements:


You can remove elements in two ways:


  1. remove(Object element)
  2. remove(int index)

remove(Object element) removes that element in the list, if it is present. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1.

remove(int index) removes the element at the given index. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1.

 

Iterating over elements:


This can be done in many ways, like using iterator, foreach style for loop, simple for loop with get method :

//access via Iterator
Iterator iterator = listA.iterator();
while(iterator.hasNext(){
String element = (String) iterator.next();
}


//access via new for-loop i.e. foreach style
for(Object object : listA) {
String element = (String) object;
}

//old style for loop
for(int i = 0;i<listA.size();i++) {
String element = listA.get(i);
}

Wednesday, September 22, 2010

The List interface

A List is an ordered Collection (sometimes called a sequence).(Sets are unordered collections)
Unlike sets, Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for:
  • Positional Access: manipulate elements based on their numerical position in the list.
  • Search: search for a specified object in the list and return its numerical position.
  • List Iteration: extend Iterator semantics to take advantage of the list's sequential nature.
  • Range-view: perform arbitrary range operations on the list.

The List interface is shown below:

public interface List extends Collection {
// Positional Access
Object get(int index);
Object set(int index, Object element);
// Optional
void add(int index, Object element);
// Optional
Object remove(int index);
// Optional
abstract boolean addAll(int index, Collection c);
// Optional // Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator listIterator();
ListIterator listIterator(int index);
// Range-view
List subList(int from, int to);
}


Comparing List to Vector


ListIterator Interface


List Implementations in java


Operations on Lists


Generic Lists in Java


Performance of List implementations in java

Chitika