2

I am basically trying to do a check of a Map in Java. My code is as follows.

private boolean isValid(Map<?,?> map) {
 return (null != map && map.size() > 0);
}

Why can't I use this method as follows?

Map<String, String> m = new HashMap<>();
isValid(m);

In Eclipse, I get the following error message:

The method isValid(Map<?,?>) in the type MyClazz is not applicable for the arguments (Map<String,String>)

As I am writing this question, I tried the following and it "works".

isValid( (Map<?,?>) m);

Why is this? Thumbing through the SO posts, I got a "similar" problem stating the problem of wildcard capture. But it doesn't seem like that's the problem here (without casting).

Jane Wayne
  • 8,205
  • 17
  • 75
  • 120

1 Answers1

0

This error does not occur with the example you've provided in either Java 8's javac or Eclipse Mars. You might try refreshing your project or cleaning the project (Project > Clean...), but otherwise your example does not replicate your actual problem.

One possibility is you're importing some other Map than java.util.Map.

This example compiles without issue, both with javac and Eclipse.

$ cat Demo.java 
import java.util.*;

class Demo {
  // isEmpty() is a better way to check if a Map is empty rather
  // than .size() > 0, which is O(n) for some Map implementations.
  public static boolean nonEmpty(Map<?,?> map) {
    return map != null && !map.isEmpty();
  }

  public static boolean nonZero(Map<?,?> map) {
    return null != map && map.size() > 0;
  }

  public static void main(String[] args) {
    nonEmpty(new HashMap<String, String>());
    nonZero(new HashMap<String, String>());
  }
}

$ javac Demo.java; echo $?
0
dimo414
  • 47,227
  • 18
  • 148
  • 244