java - Generic Types & the toArrayMethod -
java - Generic Types & the toArrayMethod -
i have class mystack<t>
defines following
public t[] toarray(){ int s=size(); @suppresswarnings("unchecked") t[] result=(t[])new object[s]; node n=first; (int i=0; i<s; i++){ result[i]=n.data; n=n.next; } homecoming result; }
since returns array of type t
, think if declared instance: mystack<string> s=new mystack<>
, next valid: string[] test=s.toarray()
. think because since s
of type string
, toarray
should homecoming array of type string
, since string
has been substituted in every t
in class (only particular instantiation, know). way runs without errors if this: object[] test=s.toarray()
.
why this?
well, hold on minute. suppose hypothesis right string
substituted every t
.
would next cast valid?
string[] result = (string[])new object[s];
no, not. can sure new object[]
not string[]
.
now see (t[])new object[n]
works because cast becomes erased within generic class. (it deceptive idiom.)
when class gets compiled, happens references t
replaced upper bound (probably object
unless had <t extends ...>
):
public object[] toarray(){ int s=size(); object[] result=new object[s]; node n=first; (int i=0; i<s; i++){ result[i]=n.data; n=n.next; } homecoming result; }
and cast moved phone call site:
mystack stack = new mystack(); string[] arr = (string[])stack.toarray();
so in fact, while cast erased within class, cast happen 1 time value returned outside class, classcastexception
thrown.
the inability instantiate arrays (and objects in general) generically why collections framework defines toarray
method take homecoming array argument. simple version of following:
public t[] toarray(t[] inarray){ int s = size(); node n = first; (int = 0; < s; i++){ inarray[i] = n.data; n = n.next; } homecoming inarray; }
for ideas on how create array generically, may see 'how create generic array in java?'; need caller pass argument method.
java generics types casting
Comments
Post a Comment