this question has answer here:
- how create generic array in java? 28 answers
i have following method:
public static <t, u> t[] getkeysforvalue(map<t,u> map,u value){ if(map == null || map.isempty()) { return null; } set<t> keys = new hashset<t>(); (map.entry<t,u> entry : map.entryset()) { if (entry.getvalue().equals(value)) { keys.add(entry.getkey()); } } return keys.toarray(new t[keys.size()]); }
i getting compilation error on line: keys.toarray(new t[keys.size()])
, says "cannot create generic array of t", obvious. how can solve issue?
you should pass class corresponding t
argument of method , call array.newinstance(clazz, size)
public static <t, u> t[] getkeysforvalue(class<t> clazz, map<t,u> map,u value){ t[] array = (t[])array.newinstance(clazz, size);
Comments
Post a Comment