【问题标题】:Adding objects from one class to an ArrayList in another class将一个类中的对象添加到另一个类中的 ArrayList
【发布时间】:2017-12-20 06:28:00
【问题描述】:

我是 java 新手,我正在尝试编写我的第一个“更大”的程序,其中包含几个类。我在“CompetitionProgram”类中创建了一个 ArrayList,并将其声明为私有。

public class CompetitionProgram {

private ArrayList<ListOfEvents> eventList = new ArrayList<ListOfEvents>();

在“addEvent”方法中,我创建了一个Event类的对象:

    private void addEvent() {

    System.out.print("Event name: ");
    String eventName = checkInput();

    System.out.print("Attempts allowed: ");
    int noOfAttempts = readInt();

    Event ev = new Event(eventName, noOfAttempts);
    eventList.add(ev);

事件类:

public class Event {

private String eventName;
private int noOfAttempts;

public Event(String eventName, int noOfAttepmts) {
    this.eventName = eventName;
    this.noOfAttempts = noOfAttepmts;
}

public String getEventName() {
    return eventName;
}

public int getNoOfAttempts() {
    return noOfAttempts;
}

ListOfEvents-class(还没完,我知道我不能返回“事件”等):

public class ListOfEvents {
public ListOfEvents() {

}

public Event addEvent(eventName, noOfAttempts) {
    // code  -add event to the list
    // code
    return event;
}

public Event findEvent(eventName) {
    // code -check if event already is in the list
    // code
    return event;
}

public boolean isEvent(eventName) {
    //code  -check if input is empty
    //code
    return true or false;
}

我想将 Event 对象添加到顶部声明的 ArrayList 中,但我不能,因为 ArrayList 是“ListOfEvents”类的列表。所以,我的问题是将 Event 对象添加到 ListOfEvents 类的 ArrayList 中。

我的程序中需要这两个类(Event 和 ListOfEvents),这是要求之一。 事件 - 仅代表事件本身,如事件名称和尝试次数(它是一项体育赛事)。而 ListOfEvents - 表示列表本身并包含添加事件、删除事件和检查事件是否已在列表中等方法。

谁知道如何解决这个问题?

【问题讨论】:

  • 也发布 ListOfEvents。名称在这里具有误导性。 ListOfEvents 应该可能包含一个列表,而不是添加到列表中的类。
  • ListOfEvents list = new ListOfEvents(); list.add(ev); eventList.add(list);

标签: java object arraylist add


【解决方案1】:

您的意思是创建一个“事件列表”列表。 如果是这样,下面的代码就可以正常工作了。

ListOfEvents list = new ListOfEvents();
Event ev = new Event(eventName, noOfAttempts);
list.add(ev);
eventList.add(list);

【讨论】:

    【解决方案2】:

    我不太确定,如果我错过了什么,但我认为,有一个简单的解决方案:

    --> 只需将 ArrayList 的泛型类型从“ListOfEvents”更改为“Event”即可:

    private ArrayList<Event> eventList = new ArrayList<Event>();
    

    这将创建“事件”类型的单个实例的可扩展列表。

    因此,作为说明性示例,以下 sn-p 将创建单个字符串的 ArrayList:

    private ArrayList<String> eventList = new ArrayList<String>();
    

    还是想创建“事件”列表?正如你所说,这是关于体育赛事的。因此,也许您想创建游戏,使用事件构建,并将这些游戏添加到列表中。在这种情况下,您可以这样工作:

    private ArrayList<ArrayList<Event>> eventList ...
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 2013-02-10
      • 2017-05-07
      • 1970-01-01
      • 2017-05-27
      • 2021-12-10
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多