gpt4 book ai didi

java - 数组列表插入方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:16 25 4
gpt4 key购买 nike

我想在数组中插入一个元素。我的方法应该是将数组的大小增加一个并将元素插入适当的位置。问题:它将元素添加到适当的位置并扩展数组,但它摆脱了该位置的原始元素并插入了一个空值。我的代码:

 public void insert(int point, Person person){
Person [] newList = new Person[this.size()+1];
for(int i = 0; i < point; i++){
newList[i] = list[i];
}
newList[point] = person;

for(int i = point+1; i<this.size(); i++){
newList[i] = list[i];

}
this.list = new Person[this.size()+1];
for(int i = 0; i <this.size(); i++){
list[i] = newList[i];
}
}

数组输出:

> FBArrayList name = new FBArrayList()
[DrJava Input Box]
> name.list[0] = new Person("Emma", 7)
Person@20a3d02a
> name.list[1] = new Person("Daniel", 8)
Person@6e8a93de
> name.list[2] = new Person("Bradley", 9)
Person@327556d1
> name.list[3] = new Person("Monica", 1)
Person@3d886c83
> name.list[4] = new Person("Connor", 2)
Person@76b41f9c
> name.list[5] = new Person("Fedor", 3)
Person@462a5d25
> name.insert(3, new Person("David", 4))
> for(int i = 0; i<7; i++){
System.out.println(name.list[i].getName());
}
Emma
Daniel
Bradley
David
Connor
Fedor
java.lang.NullPointerException
> name.list
{ Person@20a3d02a, Person@6e8a93de, Person@327556d1, Person@1d1a8b9, Person@76b41f9c, Person@462a5d25, null }

关于我为什么失去 Monica 或我可能如何解决它的任何建议。

最佳答案

public void insert(int point, Person person){
Person [] newList = new Person[this.size()+1];
for(int i = 0; i < point; i++){
newList[i] = list[i];
}
newList[point] = person;

// this part copies the remainder of the original list to the new list after
// your inserted entry
for(int i = point; i < this.size(); i++){
newList[i+1] = list[i];

}

this.list = newList;
}

关于java - 数组列表插入方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21618901/

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