我怎样才能把这个数组变成一个做同样事情的ArrayList? [英] How can I turn this array into an ArrayList that does the same thing?
问题描述
我想把这个程序的数组变成ArrayList.到目前为止,我知道该数组将变为
I want to make turn this program's array into an ArrayList. So far I know that the array will turn into
ArrayList<StudentList> list = new ArrayList<StudentList>();
,每个列表[i]都会变成:
and that each list[i] will turn into:
list.get(i)
但是我不确定以下行将满足ArrayList版本
however I am not sure what the following line will be in order to satisfy the ArrayList version
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个数组索引
new StudentList[5]
is an array of size 5, with all values null
, so you create 5 objects using new StudentList()
and assign to the 5 array indexes.
但是,new ArrayList()
创建一个空列表(大小为0).请注意,new ArrayList(5)
还会创建一个空列表,它刚刚进行了优化以存储5个元素.因此,您需要创建并添加 5个对象:
However, new ArrayList()
creates an empty list (size 0). Note that new ArrayList(5)
also creates an empty list, it is just optimized to store 5 elements. So you need to create and add 5 objects:
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();
}
在这两种情况下,最终的大小都是5的list
,其中包含5个对象.
In both cases you end up with a list
of size 5, with 5 objects.
这篇关于我怎样才能把这个数组变成一个做同样事情的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!