Java arraylist sublist example

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

public class SubListofArrayList {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();

		/*
		 * add() method appends the specified element to the end of given list.
		 */
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);
		list.add(5);
		list.add(6);
		list.add(7);

		/*
		 * List Interface has a method subList(fromIndex, toIndex) which is used
		 * to returns a view of the portion of given list between the specified
		 * fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and
		 * toIndex are equal, the returned list is empty.) The returned list is
		 * backed by this list, so non-structural changes in the returned list
		 * are reflected in given list, and vice-versa.
		 */
		List<Integer> subList = list.subList(1, 6);

		for (int i : subList)
			System.out.println(i);

		/*
		 * If the value of toIndex is greater then the size+1 of given list then
		 * JVM will throw java.lang.IndexOutOfBoundsException.
		 * 
		 * fromIndex should always be greater then toIndex. Otherwise JVM will
		 * throw java.lang.IllegalArgumentException
		 * 
		 * Below code will throw given exception as 8 > 8(Size of List) +1
		 */
		System.out.println("----");
		list.subList(6, 5);
	}
}

 

By | 2012-09-18T13:48:43+00:00 September 18th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment