-1

Is there a way to achieve something like this? This code is similar to what I want to achieve.

public static void main(String[] args){
    MultiCall(new HashMap<Integer, Integer>(){{
        put(1, 2);
        put(3, 4);
    }}, (i, j) -> {
        System.out.println(i + j);
    });

}

public void MultiCall(HashMap<?, ?> map, BiConsumer<? super ?, ? super ?> func){
    ...
    map.forEach(func);
}

The problem here is BiConsumer, I need the wildcard to be the super of HashMap's wildcard.

The linter says this

Required type: BiConsumer <? super capture of ?, ? super capture of ?>

However, upon doing ? super ?, says it need to be a Type. But the Type currently is a wildcard.

Izzuddin667
  • 83
  • 10
  • 1
    Side note: [Double brace initialization is bad.](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java) Avoid doing it. As of Java 9, you can write `Map.of(1, 2, 3, 4)` instead. – VGR Apr 10 '21 at 15:33
  • I see, I also wasn't aware that it could create a memory leak. Thanks – Izzuddin667 Apr 11 '21 at 13:09

1 Answers1

3

You need to make your method generic by adding type parameters for the map's key and value types:

public <K, V> void MultiCall(
    HashMap<K, V> map,
    BiConsumer<? super K, ? super V> func){
Andy Turner
  • 137,514
  • 11
  • 162
  • 243