将对象从一个类添加到另一个类中的ArrayList

时间:2017-07-15 06:04:42

标签: java object arraylist add

我是java的新手,我试图写下我的第一个"更大的"程序,有几个类。我已经在类" CompetitionProgram"中创建了一个ArrayList。并且它被宣布为私人。

button.frame = CGRect(x: 0, y: 0, width: 50, height: 100)

public class CompetitionProgram {

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

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

活动类:

    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);

ListOfEvents-class(它没有完成,我知道我不能返回&#34;事件&#34;等等):

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;
}

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

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

有任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您的意思是创建&#34;事件列表&#34;的列表。 如果是这样,以下代码将正常工作。

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

答案 1 :(得分:0)

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

- &GT;只需从&#34; ListOfEvents&#34;更改ArrayList的泛型类型。到&#34;事件&#34;:

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

这将创建一个类型为&#34; Event&#34;的单个实例的可伸缩列表。

因此,作为一个说明性示例,以下代码段将创建单个字符串的ArrayList:

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

或者想要创建&#34;事件&#34;?的列表列表正如你所说,这是关于体育赛事。因此,您可能希望创建使用事件构建的游戏,并将这些游戏添加到列表中。在这种情况下,您可以这样工作:

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