java - Why does android studio warn me about generic array creation for typed entry -
i have adapter in android project takes in reusable map , simplicity keeps array of data use.
private entry<string, string>[] mdata; public myadapter(@nonnull map<string, string> data) { mdata = (entry<string, string>[]) data.entryset().toarray(); }
now wanted make little more efficient , rid of unchecked warning, changed using specific array type
mdata = data.entryset().toarray( new entry<string, string>[ data.size() ] );
however new entry<string, string>[ data.size() ]
part flagged "generic array creation" no further information. why illegal?
i understand java has type erasure , generics result in different types (such explained here), above line of code still seems should legal me.
why illegal?
because arrays covariant. suppose able compile following code:
entry<string, string>[] array = new entry<string, string>[ isomap.size() ]; object[] objarray = array; // not throw arraystoreexception. objarray[0] = new abstractmap.simpleentry<>(integer.valueof(0), integer.valueof(0)); string key = array[0].getkey();
at runtime, arraystoreexception
not thrown assignment because abstractmap.simpleentry
(the runtime type of abstractmap.simpleentry<integer, integer>
) covariant map.entry
(the runtime type of entry<string, string>
) - fail classcastexception
when try execute last line because key integer
, not string
.
however, have worry every element potentially being of wrong type - given reference entry<string, string>[]
, can't know how array initialized or updated, accessing given element in wrong way result in runtime exception.
(when "the wrong way", constrasting string key = array[0].getkey()
invoking array[0].tostring()
- objects have tostring()
method, not attempt cast).
the safest way avoid such situation make creation of generic arrays illegal.
note different case of non-generic-but-covariant arrays:
string[] array = new string[1]; object[] objarray = array; // throws arraystoreexception. objarray[0] = integer.valueof(0);
because assignment throw arraystoreexception
, value of wrong type can never added array.
as such, although still have worry arraystoreexception
when trying put value array, don't have worry classcastexception
s when reading value array.
Comments
Post a Comment