将ArrayList列表中某范围对象取出,选用subList(int fromIndex, int toIndex) 方法,用ArrayList接收,报类型转换异常,java.util.ArrayList$SubList不能转换为ArrayList,为什么啊?
ArrayList<Type> resPage = (ArrayList<Type>) types.subList(5, 10);
java.lang.ClassCastException: java.util.ArrayList$SubList cannot be cast to java.util.ArrayList
at com.hyg.membership.component.impl.TypeServiceImpl.findTypePages(TypeServiceImpl.java:209) ~[classes/:na]
at com.hyg.membership.component.impl.TypeServiceImpl$$FastClassBySpringCGLIB$$f26a7431.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy.invokeMethod(CglibAopProxy.java:386) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy.access$000(CglibAopProxy.java:85) ~[spring-aop-5.3.22.jar:5.3.22]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:704) ~[spring-aop-5.3.22.jar:5.3.22]
at com.hyg.membership.component.impl.TypeServiceImpl$$EnhancerBySpringCGLIB$$feaa67c.findTypePages(<generated>) ~[classes/:na]
但是直接用List接收数据然后转换为ArrayList缺不会报错,为什么这么设计,是有什么玄奥没被参透吗?(jdk1.8.45)
List<Type> resPage = types.subList(start,end);
ArrayList<Type> data = resPage;
这个方法在List中定义是下面这样的,不过若返回的实际类型是ArrayList的话,还是可以强制转型的。
List<E> subList(int fromIndex, int toIndex)
不过,ArrayList中这个方法的实际返回类型为Sublist,它是AbstractList的子类,而非ArrayList的子类,所以无法转型。
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}