【问题标题】:Cannot instantiate the type Pair although not abstract尽管不是抽象的,但无法实例化类型 Pair
【发布时间】:2017-08-20 16:02:01
【问题描述】:

尝试编写一个返回 Pair 的迭代器: 我的 PairIterator 的一部分

public Pair next() {
            this.counter ++;
            Pair p = new Pair(this.l.get(counter - 1), this.l.get(counter)); 
            //error occurs here

        }

public class Pair<E> {
    private E e1;
    private E e2;

    public Pair(E e1, E e2) {
        this.e1 = e1;
        this.e2 = e2;
    }
    public E first() {
        return this.e1;
    }
    public E second() {
        return this.e2;
    }
}

得到

无法实例化类型 Pair

...虽然 Pair 不是抽象类/接口。为什么会这样?

【问题讨论】:

标签: java generics instantiation


【解决方案1】:

确保导入正确的类来初始化您的配对对象。

import org.apache.commons.math3.util.Pair;

具体类 -> 可以直接创建对象。

这给出了一个错误:

import org.apache.commons.lang3.tuple.Pair;

它是一个抽象类,所以不能直接创建对象。

【讨论】:

    【解决方案2】:

    尝试实例化org.apache.commons.lang3.tuple.ImmutablePair(或org.apache.commons.lang3.tuple.MutablePair);这些类是具体的,因此可以实例化。

    【讨论】:

      【解决方案3】:

      很可能是因为您没有向 Pair 添加泛型类型参数。

      【讨论】:

        猜你喜欢
        • 2013-03-07
        • 2013-05-13
        • 1970-01-01
        • 2013-12-04
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        相关资源
        最近更新 更多