【问题标题】:Incompatible types error with ArrayListArrayList 的类型不兼容错误
【发布时间】:2012-10-19 08:28:43
【问题描述】:

在我的 Java 类中,我定义了这个属性:

private ArrayList requests;

这是类中的构造函数:

public LeaveRecord() {
    this.requests = new ArrayList<Request>();
    this.daysLeft = ALLOWANCE;
}

在另一种方法中,我试图根据 ArrayList 的索引返回相关的 Request 对象。

public Request getRequestAt(int index) {
    try {
        return this.requests.get(index);
    } catch (IndexOutOfBoundsException e) {
        return null;
    }
}

但我在返回行(上述 sn-p 中的第 3 行)上遇到错误,说它需要 leaverecord.Request 但找到 java.lang.Object

我不知道有什么问题,因为我将 ArrayList 定义为 Request 类型。

有人能指出我正确的方向吗?谢谢。

【问题讨论】:

    标签: java types arraylist


    【解决方案1】:

    改成

    private ArrayList requests;
    
    private ArrayList<Request> requests
    

    但是当你说

    时编译器应该会向你显示以下警告
     private ArrayList requests;
    

    ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized

    【讨论】:

    • 或者可能是List&lt;Request&gt;(以减少与接口的耦合和代码)。也许让它final。旧代码也应该生成关于缺少类型注释的编译器警告。
    猜你喜欢
    • 2013-10-29
    • 2018-03-11
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2013-09-23
    • 2011-07-18
    相关资源
    最近更新 更多