簡體   English   中英

將對象從一個類添加到另一個類的ArrayList中

[英]Adding objects from one class to an ArrayList in another class

我是Java的新手,我正嘗試編寫第一個帶有多個類的“更大”程序。 我在“ CompetitionProgram”類中創建了一個ArrayList,並將其聲明為私有。

public class CompetitionProgram {

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

在方法“ addEvent”中,我正在創建事件類的對象:

    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類(尚未完成,我知道我無法返回“事件”等):

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”類的列表。 所以,我的問題是將事件對象添加到類ListOfEvents的ArrayList中。

我的程序中需要這兩個類(Event和ListOfEvents),這是要求之一。 事件 -僅代表事件本身,例如事件名稱和嘗試次數(它是一項體育賽事)。 ListOfEvents-代表列表本身,並包含添加事件,刪除事件以及檢查事件是否已在列表中的方法等。

有任何想法如何解決這個問題的人嗎?

您的意思是創建“事件列表”列表。 如果是這樣,下面的代碼將正常工作。

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

我不確定,如果我錯過了什么,但是我認為,有一個簡單的解決方案:

->只需將ArrayList的通用類型從“ ListOfEvents”更改為“ Event”:

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

這將創建“事件”類型的單個實例的可伸縮列表。

因此,作為一個說明性示例,以下代碼片段將創建一個包含單個字符串的ArrayList:

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

還是要創建“事件”列表的列表? 正如您所說,這是關於體育賽事的。 因此,也許您想創建帶有事件的游戲,並將這些游戲添加到列表中。 在這種情況下,您可以通過以下方式工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM