java - 在将对象添加到数组时动态增加数组长度
问题描述
我编写了一个将对象添加到对象数组的方法。如果数组已满,它应该创建一个新数组并使用 Arrays.copyOf 将旧数组大小加倍。但是,它会成功增加数组大小,但它会用旧数组中最后一个对象的副本填充新插槽。
这是 ClassRoster 类的 add 方法:
void add(Student newStudent){
int i=0;
while(i != classSize){
if(roster[i] == null{
roster[i] = newStudent;
break;
}
if(i>=roster.legnth){
Student[] newRoster = Arrays.copyOf(roster, 2*roster.length);
roster = newRoster;
}
i++;
}
}
ClassRoster 类还有一个构造函数,该构造函数使用大小为 10 的数组进行初始化。
public class ClassRoster{
private Student[] roster;
final int SIZE = 10;
public ClassRoster(){
this.roster = new Student[SIZE];
}
main 方法使用此方法从输入文本文件中添加 Student 对象:
ClassRoster firstRoster = new ClassRoster();
scan = new Scanner(inputFile).useDelimiter(",|\\n");
while(scan.hasNext()){
String name = scan.next();
int gradeLevel = scan.nextInt();
int testGrade = scan.nextInt();
Student newStudent = new Student(name,gradeLevel,testGrade);
firstRoster.add(newStudent);
System.out.printf(firstRoster.toString());
}
文本文件如下所示:
John,12,95
Mary,11,99
Bob,9,87
Larry,10,90
Steph,11,89
James,12,95
Susan,11,88
Harry,9,78
Ann,10,92
Holly,9,86
Sammy,12,75
Jen,11,90
Katrina,9,94
但是,该程序会产生如下输出:
John,12,95
Mary,11,99
Bob,9,87
Larry,10,90
Steph,11,89
James,12,95
Susan,11,88
Harry,9,78
Ann,10,92
Holly,9,86
Holly,9,86
Holly,9,86
Holly,9,86
似乎它只是在旧数组的最大大小达到 10 后复制了最后一个对象。在 Holly 之后,它不会打印出其余的学生。
解决方案
想通了问题。该数组的大小从未翻倍或增加。数组的大小仍然为 10,因为它永远不会在 add 方法中重新进入 while 循环,因为while(i != classSize)
现在为 false。因此,代码永远不会到达if (i>=roster.length)
方法的部分,也不会增加数组的大小。该程序不断打印 Holly 的副本,因为这scan.hasNext()
是真的。它不断将数组中的最后一个对象返回到
System.out.printf(firstRoster.toString());
. 它只是打印到控制台,但实际上并未分配给数组中的索引。
对于解决方案,我只是修改了add方法中的while语句:
while(i != classSize || i >= roster.length)
解决方案
如果与 thenclassSize
相同,roster.length
则应在将数组大小加倍时更改其值(尽管您不应保留单独的变量,因为roster.length
除非您需要它用于其他用途)。
当您将数组的大小加倍时,您可以在该classSize
位置添加新项目(classSize
仍然等于先前的大小)并打破循环:
void add(Student newStudent){
int i=0;
while(i != classSize){
if(roster[i] == null{
roster[i] = newStudent;
break;
}
if(i >= roster.legnth){
Student[] newRoster = Arrays.copyOf(roster, 2 * roster.length);
roster = newRoster;
roster[classSize] = newStudent;
classSize = roster.length;
break;
}
i++;
}
}
推荐阅读
- c# - FTP、SFTP 或套接字
- php - 使用 HTML 和 PHP 生成 MPDF 到 PDF
- java - 为互斥请求参数设计 API 的更好方法是什么?
- polymorphism - 在 ocaml 中定义多态中缀运算符
- xcode - Xcode 10.1 在编译时冻结
- android - 微调器值未存储在 firebase 数据库中
- c++ - 变量没有改变?通过向量的函数调用
- syntax-highlighting - 使用特定版本的atoms语言包
- python - 使用python调用antiword将doc转为txt,发现返回值是乱码
- php - VPS:切换了 PHP 版本但仍然无法安装 symfony4