Thursday, 19 May 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);
}

No comments:

Post a Comment