Clean Java

There is always a bigger game

Ordered list in java.

leave a comment »

ArrayList implementations in java maintain the order of elements. List also provides index based access and index based addition also into collection. If you have too many random accessing of elements and the order of the elements needs to be maintained a list implementation is the ideal choice. Below given simple program will explain all the above mentioned points.


package org.sanju.collection;

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

/**
 * 
 * @author sanju.org
 * @date 31st July, 2011
 * 
 * Ordered list in java.
 *
 */

public class OrderedListExample {

	public static void main(String args[]){
		
		//ArrayList declaration, always program against the
		//interface
		List list = new ArrayList();
		
		for(int i = 0; i<10; i++){
			list.add(i);
		}
		
		System.out.println("Size of the list : "+list.size());
		//list maintain the order of elements
		for(Object o : list){
			System.out.println(o);
		}
		
		//add five into the fifth position of the list
		list.add(5, "five");
		
		System.out.println("Size of the list : "+list.size());
		//list maintain the order of elements, 'five' is added
		//into the fifth position and subsequent elements shifted
		//to right to accommodate 'five' on the fifth position. 
		for(Object o : list){
			System.out.println(o);
		}
		
		//list provides API to remove elements using index.
		//all elements subsequent to position 7 would be 
		//shifted to the left.
		System.out.println("what is removed from seventh position : "+list.remove(7));
		
		//list provides index based also, if you have random 
		//access of elements from a collection then list is the ideal choice.
		System.out.println("what is in the third position : "+list.get(3));
	}
}

Console Output
————–

Size of the list : 10
0
1
2
3
4
5
6
7
8
9
Size of the list : 11
0
1
2
3
4
five
5
6
7
8
9
what is removed from seventh position : 6
what is in the third position : 3

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 33 other followers

%d bloggers like this: