我想把这个程序的数组变成一个ArrayList。到目前为止,我知道数组将变成
ArrayList<StudentList> list = new ArrayList<StudentList>();
并且每个 list[i] 将变成:
list.get(i)
但是我不确定以下行是什么以满足 ArrayList 版本
list[i] = new StudentList();
所以这里是完整的代码:
public static void main(String[] args) {
StudentList[] list = new StudentList[5];
int i;
for (i = 0; i < list.length; ++i) {
list[i] = new StudentList();
System.out.println("\nEnter information of Student _" + (i + 1) + "\n");
list[i].DataUserPrompt();
}
for (i = 0; i < list.length; ++i) {
list[i].DisplayStudentData();
}
File file12 = new File("s_records.txt");
try {
PrintWriter output = new PrintWriter(file12);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
new StudentList[5]
是一个大小为 5 的数组,包含所有值null
,因此您可以使用new StudentList()
5 个数组索引创建 5 个对象并将其分配给 5 个数组索引。
但是,new ArrayList()
创建一个空列表(大小为 0)。请注意,new ArrayList(5)
它还创建了一个空列表,它只是优化为存储 5 个元素。所以你需要创建并添加5 个对象:
List<StudentList> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
list.add(new StudentList());
}
以上等价于数组代码:
StudentList[] list = new StudentList[5];
for (int i = 0; i < 5; i++) {
list[i] = new StudentList();
}
在这两种情况下,您最终都会list
得到大小为 5 的 5 个对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句