gpt4 book ai didi

java - 数组作为实例变量

转载 作者:行者123 更新时间:2023-12-02 07:56:16 24 4
gpt4 key购买 nike

我有一个数组(moduleList)作为我的类CourseYear中的四个私有(private)实例变量之一。我希望能够在不同的类 CourseYearTestApplication 中添加数组对象的名称。到目前为止,我的 CourseYear 类(class):

public class CourseYear
{
private String courseName;
private int year;
private String tutorName;
private Module [] moduleList;

public CourseYear()
{
courseName = "Default";
year = 0;
tutorName = "Joe Bloggs";
moduleList = new Module[6];
}

public void setCourseName(String newCourseName)
{
courseName = newCourseName;
}

public void setYear(int newYear)
{
year = newYear;
}

public void setTutorName(String newTutorName)
{
tutorName = newTutorName;
}

public String getCourseName()
{
return courseName;
}

public int getYear()
{
return year;
}

public String getTutorName()
{
return tutorName;
}
}

我知道这是我的添加方法,但我不确定如何在测试中输入我的数组值(字符串)

public void addModule(Module module1, int index)
{
moduleList[index] = module1;
}


public Module getModule(int index)
{
return moduleList[index];
}

这是我迄今为止的CourseYearTestApplication

public class CourseYearTestApplication
{
public static void main (String [] args)
{
CourseYear courseYear1 = new CourseYear();

courseYear1.addModule(new Module(), 0);
courseYear1.addModule(new Module(), 1);
courseYear1.addModule(new Module(), 2);
courseYear1.addModule(new Module(), 3);
courseYear1.addModule(new Module(), 4);
courseYear1.addModule(new Module(), 5);
}
}

最佳答案

为什么不使用 ArrayList 来代替呢?这将允许您根据需要增大/缩小数组,并且很好地遵循您的 API 要求:

public class CourseYear {
private String courseName;
private int year;
private String tutorName;
private List<Module> moduleList = new ArrayList<Module>;
....

public void addModule(Module module1, int index) {
moduleList.add(module1);
}


public Module getModule(int index) {
return moduleList.at(index);
}


}

关于java - 数组作为实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9591635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com