Sub Collections
suggest changeList subList(int fromIndex, int toIndex)
Here fromIndex is inclusive and toIndex is exclusive.
List list = new ArrayList();
List list1 = list.subList(fromIndex,toIndex);
- If the range is outside the list, it throws
IndexOutOfBoundsException. - Whatever changes are made on
list1also changelist. This is called a backed collection. - If
fromIndexis greater thantoIndex, it throwsIllegalArgumentException.
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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents