首页 > 解决方案 > 泛型编译错误。无法修复

问题描述

我正在尝试学习泛型并遇到了这个问题。我很困惑为什么代码不起作用

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 类型的封闭实例来限定分配(例如 xnew A(),其中 x 是 Test 的实例)。

标签: javagenerics

解决方案


您的代码几乎没有问题

  1. new Pair<String, Double>不适用于<K, V extends Integer>as Doubledoesn't extend Integer。一种方法是Number根据此答案重新定义方法以考虑 Number 的不同实现

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

推荐阅读