I am trying to learn generics and came across this question. I am very confused why the code is not working
public class Test {
public static void main(String args[]) {
int result;
result = printValues(new Pair<String, Double>("Pair1", 3.0), new
Pair<String, Double>("Pair2", 4.0));
System.out.println(result);
}
public static <K, V extends Integer> int printValues(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getValue() + p2.getValue();
}
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public void setKey(K key) {
this.key = key;
}
public void setValue(V value) {
this.value = value;
}
}
}
I am getting following compliation error: The method printValues(Test.Pair, Test.Pair) in the type Test is not applicable for the arguments (Test.Pair, Test.Pair) I tried to change the method printValues as follow:
public static <K, V extends Number> int printValues(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getValue() + p2.getValue();
}
But then the error is "The operator + is undefined for the argument type(s) V, V"
Edit:
public static <K, V extends Number> int printValues(Pair<K, V> p1,
Pair<K, V> p2) {
return p1.getValue().intValue() + p2.getValue().intValue();
}
Now i get error on printValues(new Pair
No enclosing instance of type Test is accessible. Must qualify the allocation with an enclosing instance of type Test (e.g. x.new A() where x is an instance of Test).