与ArrayList不兼容的类型错误

Jam*_*son 0 java types arraylist

在我的Java类中,我定义了以下属性:

private ArrayList requests;
Run Code Online (Sandbox Code Playgroud)

这是类中的构造函数:

public LeaveRecord() {
    this.requests = new ArrayList<Request>();
    this.daysLeft = ALLOWANCE;
}
Run Code Online (Sandbox Code Playgroud)

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

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

但是我在返回行(上面代码段中的第3行)上收到了一个错误,说它需要leaverecord.Request但是找到了java.lang.Object.

我不知道会出现什么问题,因为我将ArrayList定义为类型Request.

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

Per*_*ror 5

改为

private ArrayList requests;

private ArrayList<Request> requests
Run Code Online (Sandbox Code Playgroud)

但是,当您说时,编译器应该向您显示以下警告

 private ArrayList requests;
Run Code Online (Sandbox Code Playgroud)

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

  • 或者可能是`List <Request>`(以减少耦合和代码到接口).也许让它成为'最终'.旧代码也应该生成一个关于缺少类型注释的编译器警告. (2认同)