泛型编译错误。无法修复

时间:2018-08-07 09:05:10

标签: java generics

我正在尝试学习泛型,并遇到了这个问题。我很困惑为什么代码无法正常工作

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;
        }

    }
}

我收到以下错误提示: 类型为Test的方法printValues(Test.Pair,Test.Pair)不适用于这些参数  (Test.Pair,Test.Pair) 我试图更改方法printValues如下:

public static <K, V extends Number> int printValues(Pair<K, V> p1, Pair<K, V> p2) {
    return p1.getValue() + p2.getValue();
}

但是错误是“对于参数类型V,V,运算符+未定义”

编辑:

      public static <K, V extends Number> int printValues(Pair<K, V> p1, 
        Pair<K, V> p2) {
           return p1.getValue().intValue() + p2.getValue().intValue();
         }

现在我在printValues(新对

没有可访问的Test类型的封闭实例。必须使用封闭的Test类型实例(例如x.new A(),其中x是Test的实例)对分配进行限定。

2 个答案:

答案 0 :(得分:3)

您的代码几乎没有问题

  1. new Pair<String, Double>不适用于<K, V extends Integer>,因为Double不扩展Integer。一种方法是按照this answer to account for different implementations of NumberNumber重新定义方法:

    public static <K, V extends Number> Number printValues(Pair<K, V> p1, Pair<K, V> p2) {
      if(p1.getValue() instanceof Double || p2.getValue() instanceof Double) {
        return new Double(p1.getValue().doubleValue() + p2.getValue().doubleValue());
      } else if(p1.getValue() instanceof Float || p2.getValue() instanceof Float) {
        return new Float(p1.getValue().floatValue() + p2.getValue().floatValue());
      } else if(p1.getValue() instanceof Long || p2.getValue() instanceof Long) {
        return new Long(p1.getValue().longValue() + p2.getValue().longValue());
      } else {
        return new Integer(p1.getValue().intValue() + p2.getValue().intValue());
      }
    }
    
  2. 应将Pair类声明为静态,以便可以在静态main()方法中使用它:

    static class Pair<K, V> {
    
  3. 无需声明对象的泛型类型,从Java 7开始,足以使用<>运算符:

    Number result = printValues(new Pair<>("Pair1", 3.0), new Pair<>("Pair2", 4.0));
    

答案 1 :(得分:0)

public static <K, V extends Number> int printValues(Pair<K, V> p1, Pair<K, V> p2) {
    return p1.getValue().intValue() + p2.getValue().intValue();
}

在Java中,如果将Number子类化,则不能继承+运算符(或任何其他运算符)。另一方面,方法是继承的(即intValue)