gpt4 book ai didi

java - 移动 ArrayList

转载 作者:行者123 更新时间:2023-12-01 15:30:41 27 4
gpt4 key购买 nike

我编写了一个具有 add 和 get 方法的 SortedIntList 类。

我调用以下四个方法:

SortedIntList mySortedIntList = new SortedIntList();
mySortedIntList.add(9);
mySortedIntList.add(7);
System.out.println("0 is :"+mySortedIntList.get(0));
System.out.println("1 is :"+mySortedIntList.get(1));

我的获取和添加方法如下所示:

public void add(Integer newValue) {
int position = 0;
while(position < list.size()){
int currentPosValue = list.get(position);
if(newValue <= currentPosValue){
for(int i=list.size()-1; i>=position; i--){
int toBeShifted = list.get(i);
list.set(i+1, toBeShifted);
}
list.set(position, newValue);
return;
}
position++;
}
list.add(newValue);
}


public int get(int i) throws IndexOutOfBoundsException {
// Postcondition: If i < 0 or i >= size() throws
// IndexOutOfBoundsException, otherwise returns the value
// at position i of this IntList
if (i < 0 || i >= list.size()) {
throw new IndexOutOfBoundsException("SortedIntList.get");
} else {
return ((Integer) list.get(i)).intValue();
}
}





public int get(int i) throws IndexOutOfBoundsException {
// Postcondition: If i < 0 or i >= size() throws
// IndexOutOfBoundsException, otherwise returns the value
// at position i of this IntList
if (i < 0 || i >= list.size()) {
throw new IndexOutOfBoundsException("SortedIntList.get");
} else {
return ((Integer) list.get(i)).intValue();
}
}

我已经把它写在纸上,看起来很合乎逻辑,但代码却崩溃了:

System.out.println("1 is :"+mySortedIntList.get(1)) 行,显然 1 越界,但我不知道怎么回事。

最佳答案

阅读 Java 文档会有所帮助。显然,使用 set() 要求您尝试覆盖的位置已经有一个值。我需要使用 add(position, value) 来代替:-)

关于java - 移动 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552080/

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