java - Generic list conversion to an array -
assuming have following class
public class <t>{ private t [] datas; // more code here ... }
and desire take advantage of constructor initialize array. suppose have following constructor
public a(t element){....}
java not allow me use like
datas = new t[10]
and complain cannot create generic array of t can still use work around like:
@suppresswarnings("unchecked") public a(t element){ list<t> dataslist = new arraylist<t>(); dataslist.add(element); datas =(t[]) dataslist.toarray(); }
i have warning compiler that's why had add @suppresswarnings, point related following comment toarray method documentation (please take @ picture)
it talks returned array being safe. so means safe use method? if not why? , better way such initialisation in constructor? consider case of variable list of t elements in overloaded constructor
public a(t... elements){....}.
you can create instance of generic array using following:
public a(t element){ int length = 10; datas = (t[])array.newinstance(element.getclass(), length); }
however, there's problem if element
subclass of t
, e.g. if you'd call this:
a<number> numbera = new a<>( integer.valueof(1) );
here t
number
class of element
integer
. mitigate pass vararg array of type t
, e.g. this:
//firstelement exists force caller provide @ least 1 element //if don't want use varargs array a(t firstelement, t... furtherelements){ int length = 10; class<?> elementclass = furtherelements.getclass().getcomponenttype(); datas = (t[])array.newinstance( elementclass, length); }
since varargs result in array (even of length 0) you'll array of type t
, can component type of that.
so in case above numbera.datas
number[]
array , not integer[]
array.
Comments
Post a Comment