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 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)

		 * 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
		list.subList(6, 5);


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top Search