java 中sublist的使用
转自:http://blog.csdn.net/sbfivwsll/article/details/6557611
java List.subList方法中的超级大陷阱
在使用集合中,可能常常需要取集合中的某一部分子集来进行一下操作,于是subList这个方法就映入我们的眼帘,毫不犹豫地使用。
例如以下代码:
public static void main(final String[] args) {List<Object> lists = new ArrayList<Object>();lists.add("1");lists.add("2");lists.add("3");lists.add("4");List<Object> tempList = lists.subList(2, lists.size());tempList.add("6");System.out.println(tempList); // 1System.out.println(lists); // 2} SubList(AbstractList<E> list, int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); l = list; offset = fromIndex; size = toIndex - fromIndex; expectedModCount = l.modCount; } public void add(int index, E element) { if (index<0 || index>size) throw new IndexOutOfBoundsException(); checkForComodification(); l.add(index+offset, element); expectedModCount = l.modCount; size++; modCount++; }public static void main(final String[] args) {List<Object> lists = new ArrayList<Object>();lists.add("1");lists.add("2");lists.add("3");lists.add("4");//注意这里是和本文顶部的代码不同的....List<Object> tempList = new ArrayList<Object>(lists.subList(2, lists.size()));tempList.add("6");System.out.println(tempList); // 1System.out.println(lists); // 2}