我将如何在另一个字段的存储对象中创建一个字段?

问题描述 投票:0回答:1

所以在这里,我有一个代表音乐节的表演的集体法案。

public class Act {
    private int num_members;
    private String name;
    private String kind;
    private String stage;


    public Act(int num_members, String name, String kind, String stage) {
        this.num_members = num_members;
        this.name = name;
        this.kind = kind;
        this.stage = stage;
    }

    public Act(int num_members, String name, String kind) {
        this.num_members = num_members;
        this.name = name;
        this.kind = kind;
        stage = null;
    }

    public int getNum_members() {
        return num_members;
    }

    public void setNum_members(int num_members) {
        this.num_members = num_members;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public String getStage() {
        return stage;
    }

    public void setStage(String stage) {
        this.stage = stage;
    }

    public String toString() {
        return "(" + num_members + ", " + name + ", " + kind + ", " + stage + ")";
    }
}

在另一个名为LineUp的类中,我想在名为acts的字段中存储多达30个行为,并且还有一个方法addAct,该方法将Act作为参数并将其添加到acts。这是到目前为止的代码,但是我不确定该怎么做。


public class LineUp {
    Act[] acts;


    public LineUp() {
        Act[] acts = new Act[30];
    }

    void addAct(Act a) {

    }
}
java class object field
1个回答
0
投票

[如果使用数组,则必须确保永远不要添加超过30 Act并跟踪该数字以对您有所帮助,否则,更简单的解决方案是在您不使用时使用List<Act>”无需打扰您,只需随意添加(或删除)

Array:

public class LineUp {
    Act[] acts;
    int number;

    public LineUp() {
        acts = new Act[30]; // you assign to 'this' you don't create a new one
        number = 0; 
    }

    void addAct(Act a) {
        acts[number] = a;
        number++;
    }
}

列表:

public class LineUp {
    List<Act> acts;

    public LineUp() {
        acts = new ArrayList<>;
    }

    void addAct(Act a) {
        acts.add(a);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.