Pergunta

I have class Counter with a method add which will count instances of any classes when creating but I get "The method add(Class) in the type Counter is not applicable for the arguments (MyClass)" How can I fix it? What should I type instead of Class<?> c?

public class Counter
{
    static Map<String, Integer> map = new HashMap<String, Integer>();

    public static void add(Class<?> c) 
    {
            String name = c.getClass().getSimpleName();
            int count = list.containsKey(name) ? map.get(name) : 0;
            map.put(name, count + 1);
    }
}

public class MyClass
{  
    public MyClass()
    {
        Counter.add(this); 
    }
Foi útil?

Solução

I agree with @Rohit Jain that it should be Object. I however want to suggest parameterized version of add() method:

public static <T> add(T obj) {
    Class<?> clazz = obj.getClass();
    // your implementation
}

Parameterized versions look better.

Outras dicas

Instead of changing your add method, you should change the constructor for MyClass to this:

public MyClass()
{
    Counter.add(this.getClass());
}

That way, you can use your HashMap<Class<?>, Integer> (or whatever you're using to do the actual counting) like so:

if(map.containsKey(c))
{
    map.put(c, map.get(c) + 1));
}
else
{
    map.put(c, 1);
}

There is a potential problem with this counter idea: when an object becomes unreachable and gets collected, the counter won't decrease. So your counter will not be able to tell you how many objects you currently have, but how many you have created overall.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top