Java / Generics / ClassCastException -
i have linkedlist<t>
contains object toarray()
method:
public object[] toarray() { object[] array = new object[size]; int c=0; for(node<t> = first;i != null;i=i.next) { array[c++] = i.data; } return array; }
i sort linkedlist generic method: <t extends comparable> void sort (list<t> list)
. sort lists, must represent them array in method:
t[] elements = (t[])list.toarray();`
however, classcastexception
@ line , don't know why. since generic type of method equivalent element's runtime type in returned array, cast not lie!
toarray()
returns object[]
. type information lost , can't cast t[]. if want keep type information can use following. give method predifined array filled. if don't give - toarray
create new object[]
.
t[] elements = list.toarray(new t[list.size()]);
just filling array (another writing style):
t[] elements = new t[list.size()]; list.toarray(elements);
or if use java 8:
t[] elements = list.stream().toarray(t[]::new);
Comments
Post a Comment