java - 移动 ArrayList

标签 java arraylist

我编写了一个具有 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/

相关文章:

java - 为什么setter方法不更新对象?

java - 二维阵列棋盘游戏的“撤消移动”功能实现

java - 打印奇数行时出现问题

java - ClassCastException 转换错误

Java EchoTCPServer - 发送给所有客户端

java - 使用 Gradle 执行包含依赖项的 jar

java - Java中ArrayList的归并排序

java - TicTacToe 打印棋盘

java - 使用 JGit 创建新的本地存储库失败 "with Bare Repository has neither a working tree..."

java - 从数组中提取信息