Question

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 ?)
Was it helpful?

Solution

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.

OTHER TIPS

Philip is correct in his diagnosis, but you should still be able to declare a generic type and then use it. In your case,

public <T> void set(Key<T> key) {
    for (int i = 0; i < settings.size(); i++) {
        Key<T> k = settings.get(i);
        if (k.getName().equals(key.getName())) {
            k.setValue(key.getValue()); // Error here
            break;
        }
    }
    settings.add(key);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top