Java数组:从基础到高级应用
1. 可扩展部分填充数组的初始化与添加
在处理数组时,我们常常需要动态地添加元素。以下是一个示例代码,展示了如何初始化一个可扩展的部分填充数组,并向其中添加元素:
// Read the data, adding each person to the array
Scanner in = this.openFile(fileName);
while (in.hasNextLine()) {
this.add(new Person(in));
}
in.close();
/** Add a person to the the list of persons. */
public void add(Person p) {
if (this.persons.length == this.size) {
// The array is full -- grow it.
Person[] larger = new Person[this.size * 2];
for (int i = 0; i < this.size; i++) {
larger[i] = this.persons[i];
}
this.persons = larger;
}
this.persons[this.size] = p;
this.size++;
}
上述代码的执行流程如下:
1. 打开文件并创建 Scanner 对
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



