案列
public static void main(String[] args) {
List<String> names = new ArrayList<String>() {{
add("hht1");
add("hht2");
add("hht3");
}};
ArrayList subList = names.subList(0, 1);
System.out.println(subList);
}
报错
java.lang.ClassCastException:
java.util.ArrayList$SubList cannot be cast to java.util.ArrayList
why?
jdk注释
Returns a view of the portion of this list between the
specifiedfromIndex, inclusive, and toIndex, exclusive.
意思是他是一个视图,那我可以这样理解,他没有真正的改变,只是创建了一个视图指向了它,视图的结果就是我们想要的结果
有点绕?
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
这个方法返回了一个SubList而不是ArrayList,这个类是ArrayList中的一个内部类。而不是子类,所以会
java.lang.ClassCastException:
java.util.ArrayList$SubList cannot be cast to java.util.ArrayList
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
构造函数中把原来的List以及该List中的部分属性直接赋值给自己,
SubList并没有重新创建一个List,而是直接引用了原有的List(返回了父类的视图),只是指定了一下他要使用的元素的范围而已(从fromIndex(包含),到toIndex(不包含))
SubList这个类中单独定义了set、get、size、add、remove等方法。