Java Generics With Any Type

Tags: , ,



I’m trying to write a method in Java that will be able to add a custom Key object to an array, or change an already existing key in the array if there is one. However, I can’t seem to get it to work. The types that keys will use are primarily be String and Integer, but my universal approach doesn’t seem to work.

The setValue() method has T as the parameter type, and getValue() returns T.

public void set(Key<?> key) {
    for (int i = 0; i < settings.size(); i++) {
        Key<?> k = settings.get(i);
        if (k.getName().equals(key.getName())) {
            k.setValue(key.getValue()); // Error here
            break;
        }
    }
    settings.add(key);
}

The error (I’m using Eclipse) is:

The method setValue(capture#4-of ?) in the type Key<capture#4-of ?>
is not applicable for the arguments (capture#5-of ?)

Answer

You can’t guarantee to java that if you provide a Key object to your set() method and there is an another Key object in array with the same name, that they will have the same type argument. So java can’t check type safety of your code at compile time.

So, I think, you should use Raw Types here.



Source: stackoverflow