Java / Generics / Array problems -


i understand relationship between generics , arrays finally, provide example inconsisent me, based on arraylist<t> :

object[] elementdata = new object[size]; 

this elements of generic list stored.

public void add(t element){ elementdata[size++] = element; }  public t get(int index) { return (t)elementdata[index] } 

completely works. can out underlying <t> objects, array contains references these objects object.

in contrast this:

public object[] toarray() {            object[] result = new object[size];      for(int = 0;i<size;i++)     {         result[i] = elementdata[i];     }      return result; } 

i cannot cast elements in returned array real type, whole set same: object array contains references <t> objects. got classcastexception error, when trying cast elements real type.

if collection interface, see there 2 toarray() methods:

  • object[] toarray()

    returns array containing of elements in collection.

  • <t> t[] toarray(t[] a)

    returns array containing of elements in collection; runtime type of returned array of specified array.

the reason cannot make generic arrays, return object[].

making generic method of toarray() simple:

public <t> t[] toarray(t[] arr) {            t[] result = arr.size == size ? arr : (t[])java.lang.reflect.array               .newinstance(arr.getclass().getcomponenttype(), size);      for(int = 0;i<size;i++)     {         result[i] = elementdata[i];     }      return result; } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -