0

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?

Aquarius Power
  • 3,212
  • 5
  • 26
  • 56
  • 2
    Better stick with collections to avoid arrays of generic types... Change your function code to `function(Collection> array)` and just call it using `function(hhm.values())`. You may need to change the implementation of `function` to read a collection/set rather than an array. – ernest_k Jun 02 '17 at 03:34
  • @ErnestKiwele because of this I guess? https://stackoverflow.com/a/33178372/1422630 – Aquarius Power Jun 02 '17 at 04:43
  • You could say that. It's always a good time to rethink your design or contracts when you catch yourself making arrays of generic types. And, yes, that answer gives the first reason of the challenge. – ernest_k Jun 02 '17 at 04:57
  • No, that answer isn't relevant: it's talking about `new E[...]` where `E` is a type parameter, not a generic class. See https://www.ibm.com/developerworks/java/library/j-jtp01255/index.html under "More covariance troubles" instead. – Alexey Romanov Jun 02 '17 at 07:01

2 Answers2

1

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));
        }
    }
}
Yoonsung Lee
  • 85
  • 1
  • 7
1

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).

Alexey Romanov
  • 154,018
  • 31
  • 276
  • 433