java—如何在方法中定位异常?

sr4lhrrt  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(262)

我的数据结构类正在以skiplist的形式实现自己的数据结构。我正在研究的方法是sublist。我已经处理了大多数错误,但是我得到一个错误,说在我的系统中抛出了一个异常 testSubList() 方法。我不确定这可能是什么,因为我相信我已经用输入变量覆盖了所有的错误。假设所有其他方法都起作用,是什么导致了这个错误?

public List<E> subList(int fromIndex, int toIndex)
{
  //subList method written by Ryan Schubert
//if a trivial case where the index is out of bounds occurs throw exception
  if (fromIndex < 0 || toIndex > this.size() || toIndex < fromIndex){
    throw new IndexOutOfBoundsException();
  }
//make new skiplist to add values to
    List<E> sub = new SkipList<E>();
//run through the skiplist between the indices and add the values to sub
    for(int i = fromIndex; i<toIndex; i++)
    {
        sub.add(this.get(i));
    }
    return sub;
}  
public static boolean testSubList()
    {
      //testSubList method written by Ryan Schubert
      //make a new list and add a bunch of values to it
        List<String> testList = new SkipList<String>();

        testList.add("test1");
        testList.add("test2");
        testList.add("test3");
        testList.add("test4");
        testList.add("test5");
        testList.add("test6");
        //make a new list and fill it with sub list values
        List<String> testSubList = new SkipList<String>();
        testSubList = testList.subList(1, 4);
        //compare the test list to the sublist
        if (testList.containsAll(testSubList))
        {
            System.out.println("true");
            return true;
        }
        else
        {
            System.out.println("false");
            return false;
        }
    }
4si2a6ki

4si2a6ki1#

要知道是哪行代码导致了问题,可以打印此方法引发的异常的堆栈跟踪。
你不认为在第一个for循环中,你应该替换 toIndex > this.size()toIndex >= this.size() ? 列表的最后一个索引是 size() - 1 . 例如,当列表中有3项时, size() = 3 ,但最后一项的索引是2。这意味着 this.size() 也超出了数组的界限。

相关问题