collections - java downcast results in method not applicable error -
i trying downcast function database objects. get:
the method getasstringarray(hashmap<long,dbobject>) in type dbobject not applicable arguments (hashmap<long,dbemployee>)
when try call getasstringarray(). here test code: dbobject base class:
public class dbobject implements comparable<dbobject> { protected long id; public long getid() { return id; } public void setid(long id) { this.id = id; } public static dbobject[] getasarray(hashmap<long,dbobject> map) { collection<dbobject> list = map.values(); dbobject[] ar = list.toarray(new dbobject[] {}); arrays.sort(ar); return ar; } public static string[] getasstringarray(hashmap<long,dbobject> map) { vector<string>vstrings = new vector<string>(); collection<dbobject> list = map.values(); dbobject[] ar = list.toarray(new dbobject[] {}); arrays.sort(ar); (dbobject o : ar) vstrings.add(o.tostring()); return (string[]) vstrings.toarray(new string[] {}); } @override public int compareto(dbobject another) { return (int)(this.getid() - another.getid()); } }
child class dbemployee:
public class dbemployee extends dbobject { private string first; private string last; public dbemployee(){} public string tostring() { return last + ", " + first; } }
and error:
public static void main(string[] args) { hashmap<long,dbemployee>mapemployees = new hashmap<long,dbemployee>(); dbemployee.getasstringarray(mapemployees); }
note: of dbobjects have own compareto() function (a few of objects have field in db override default sort order), of items sort id.
you need redefine method thusly:
public static dbobject[] getasarray(hashmap<long, ? extends dbobject> map) { collection<? extends dbobject> list = map.values(); dbobject[] ar = list.toarray(new dbobject[] {}); arrays.sort(ar); return ar; }
a map<long, dbemployee>
cannot used in place of map<long, dbobject>
, because although has of same behaviour, of behaviour different. in particular, can't add object of type dbobject
map<long, dbemployee>
.
if method getasarray(hashmap<long, dbobject> map)
allowed pass map<long, dbemployee>
, able add dbobjects
map inside method. method has no way know map not map of dbobjects
. then, if held on reference map outside of method, have big problems. map no longer type-safe. map<long, dbemployee>
, contain dbobjects
not dbemployees
.
the ? extends dbobject
syntax allows specify can out of map without detailing can go in it. you'll notice if try add map inside getasarray(hashmap<long, extends dbobject> map)
method, you'll compile error.
(there equivalent syntax, ? super dbemployee
, let put things in map without knowing come out).
Comments
Post a Comment