Java无法ForEach自定义类的数组列表(不兼容的类型)

时间:2017-12-30 03:44:56

标签: java arraylist foreach

当我尝试通过自定义类的对象的数组列表进行操作时,出现以下错误:错误:

"不兼容的类型:(对象)无法转换为ArrayList。"

在阅读了this one之类的其他几篇文章之后,我以为我只是在我的宣言中缺少投射或使对象类型显式化。然而,在修复它之后问题仍然存在。

ArrayList<Room> roomList = new ArrayList<Room>();

for (final ArrayList room: roomList)

我错过了什么?如果它有所作为我使用this在线编译器作为我的IDE。

import java.io.*;
import java.util.*;
class SchedulingApplication
{
    ArrayList<Room> roomList = new ArrayList<Room>();
    int roomCount = 0;
static class Meeting
{
    double startTime;
    double endTime;
}
static class Room
{
    int roomNumber = 0;
    ArrayList<Meeting> meetingList = new ArrayList<Meeting>();
}


void addNewMeeting(double start, double end)
{
    Meeting meeting = new Meeting();
    checkConflict(meeting);
    return;

}

void addNewRoom(int number)
{
    Room room = new Room();
    room.roomNumber = number;
    roomCount++;
    roomList.add(room);
}
int checkConflict(Meeting newMeeting)
{
    //boolean isScheduled = false;
    boolean isConflict = false;
    if (roomCount == 0)
    {
        roomCount++;
        return roomCount;
    }
    else
    {
            for (final ArrayList room: roomList)
            {
                isConflict = false;
                for (final ArrayList  oldMeeting: room.meetingList())
                {
                    //see if the new meeting starts during all of the old meetings in this room
                    if (newMeeting.startTime > oldMeeting.startTime && newMeeting.startTime < oldMeeting.endTime)
                    {
                        isConflict = true;
                        break;
                    }
                }
                if (!isConflict)
                {
                    //isScheduled = true;
                    return room.roomNumber();
                }
            }

    }

}

    public static void main (String[] args) {




}

}

2 个答案:

答案 0 :(得分:2)

for (Room room : roomList)不是for (ArrayList room : roomList)

答案 1 :(得分:2)

您的roomList arrayList包含Room类型的数据。因此,当您在forEach循环中从该arrayList中检索数据时,您需要在Room类型的引用中接收它。

for (Room room: roomList){
    //your code
}