我已经创建了一个新的ArrayList,我只需要向其添加实例,但是Java却说“无法解析符号'add'”。 我已经看了这个问题:(how to change from arrays to one array list),但我仍然收到错误消息
代码:
public class EventController {
ArrayList<Event> events = new ArrayList<>();
Event e1 = new Event("Drake", "5th October 2019", "19:30-late", "Leeds", "First Direct Arena");
Event e2 = new Event("Drake", "6th October 2019", "21:30-late", "Leeds", "First Direct Arena");
Event e3 = new Event("Ed Sheeran", "21st October 2019", "19:00-late", "Leeds", "First Direct Arena");
Event e4 = new Event("Ed Sheeran", "22nd October 2019", "20:30-late", "Leeds", "First Direct Arena");
Event e5 = new Event("Jorja Smith", "3rd November 2019", "19:30-late", "Leeds", "First Direct Arena");
Event e6 = new Event("Jorja Smith", "4rd November 2019", "20:30-late", "Leeds", "First Direct Arena");
Event e7 = new Event("Coldplay", "15th December 2019", "17:30-late", "Leeds", "First Direct Arena");
Event e8 = new Event("Coldplay", "16th December 2019", "19:30-late", "Leeds", "First Direct Arena");
events.add(e1);
}
答案 0 :(得分:2)
您需要将代码放入构造函数或函数中。
public class EventController {
public EventController() {
ArrayList<Event> events = new ArrayList<>();
Event e1 = new Event("Drake", "5th October 2019", "19:30-late", "Leeds", "First Direct Arena");
Event e2 = new Event("Drake", "6th October 2019", "21:30-late", "Leeds", "First Direct Arena");
Event e3 = new Event("Ed Sheeran", "21st October 2019", "19:00-late", "Leeds", "First Direct Arena");
Event e4 = new Event("Ed Sheeran", "22nd October 2019", "20:30-late", "Leeds", "First Direct Arena");
Event e5 = new Event("Jorja Smith", "3rd November 2019", "19:30-late", "Leeds", "First Direct Arena");
Event e6 = new Event("Jorja Smith", "4rd November 2019", "20:30-late", "Leeds", "First Direct Arena");
Event e7 = new Event("Coldplay", "15th December 2019", "17:30-late", "Leeds", "First Direct Arena");
Event e8 = new Event("Coldplay", "16th December 2019", "19:30-late", "Leeds", "First Direct Arena");
events.add(e1);
}
}
答案 1 :(得分:0)
您必须将类扩展为Activity,或者可以在方法中编写代码以执行ArrayList()的添加。