I have a Vector< MyClass > myvector
; with size 0 - 400 and I'd like my method to return a new Vector with the positions 0-100 if exists. But my code:
return (Vector< MyClass >) myvector.sublist( 0, Math.min(myvector.size,100) );
crashes with at the return line.
ERROR/AndroidRuntime(2053): java.lang.Cl开发者_C百科assCastException: java.util.Collections$SynchronizedRandomAccessList
What am I doing wrong? how can I fix it?
Thanks in advance
Vector<MyClass>.subList()
returns a List<MyClass>
. List<MyClass>
cannot be converted to a Vector<MyClass>
.
It's often suggested that, in general, you should work with references-to-interface-types, not references-to-concrete-types wherever possible. Following this advice avoids this sort of conundrum.
The return type of Vector.subList is not necessarily of class Vector, but rather an implementation of a List. You can solve this problem by:
return new Vector<MyClass>(myvector.subList(0, Math.min(myvector.size(), 100)));
Edit: Thanks Stjepan and Steve for noting the unnecessary conditional.
Sublist is returning a List if you want to do this you will have to do this:
new Vector(myList);
because sublist returns a list not a vector
精彩评论