Sub Collections

suggest change

List subList(int fromIndex, int toIndex)

Here fromIndex is inclusive and toIndex is exclusive.

List list = new ArrayList(); 
List list1 = list.subList(fromIndex,toIndex);
  1. If the range is outside the list, it throws IndexOutOfBoundsException.
  2. Whatever changes are made on list1 also change list. This is called a backed collection.
  3. If fromIndex is greater than toIndex, it throws IllegalArgumentException.

Example:

List<String> list = new ArrayList<String>();
list.add("Hello1"); 
list.add("Hello2"); 
System.out.println("Before Sublist "+list); 
List<String> list2 = list.subList(0, 1);
list2.add("Hello3"); 
System.out.println("After sublist changes "+list);
Before Sublist [Hello1, Hello2] After sublist changes [Hello1, Hello3, Hello2]

Set subSet(fromElement, toElement)

Here fromElement is inclusive and toElement is exclusive.

Set set = new TreeSet(); 
Set set1 = set.subSet(fromElement, toElement);

The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.

Map subMap(fromKey,toKey)

fromKey is inclusive and toKey is exclusive.

Map map = new TreeMap();
Map map1 = map.subMap(fromKey, toKey);

If fromKey is greater than toKey or if this map itself has a restricted range, and fromKey or toKey lies outside the bounds of the range then it throws IllegalArgumentException.

These sub-collections are backed by the original collection, so a change to the sub-collection changes the main collection.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents