I expect the subject is clear, suggestions are appreciated.
I have a hhm=new HashMap<String,HashMap<String,Test>>()
.
I have a function(HashMap<String,Test>... array)
.
I need to call function(hhm.values().toArray(new HashMap<String,Test>[0]))
but I cant find a way to do that, this code wont compile.
Casting will cause exception in run-time: function((HashMap<String,Test>[])hhm.values().toArray())
what now?
2 Answers 2
Hacky solution in case you can't change function
, not recommended otherwise:
function(hhm.values().toArray((HashMap<String,Test>[]) new HashMap<?,?>[0]))
Since it is legal to create a HashMap<?,?>[]
, and you can then cast it because HashMap<Whatever, Whatever>[]
is really just HashMap[]
at runtime (if it weren't, there would be no problem with new HashMap<String,Test>[0]
in the first place).
Comments
I undertand what you want to implement. But your intention is not appropriate on Java.
Collections Using Generic. The purpose of Generic is Type-Saftey on compile-time.
Java array is deficient, so it force type on run-time.
Your intention is possible to implement. But you will be more safe to change varags parameter to List and more convenient to implement your purpose.
List<Map<String, Test1>> list =new ArrayList<>();
for(String key : hhm.keySet()){
list.add(hhm.get(key));
}
function(list);
public static void function(List<Map<String, Test1>> list){
for(Map<String, Test1> map : list){
for(String key : map.keySet()){
System.out.println(key +" : "+map.get(key));
}
}
}
function(Collection<HashMap<String, Test>> array)
and just call it usingfunction(hhm.values())
. You may need to change the implementation offunction
to read a collection/set rather than an array.new E[...]
whereE
is a type parameter, not a generic class. See ibm.com/developerworks/java/library/j-jtp01255/index.html under "More covariance troubles" instead.