如何处理列表IndexOutOfBoundsException?

问题描述 投票:-1回答:2

我正在尝试为LinkedList编写get()方法,其中私有方法由公共方法使用,但是我一直在获取IndexOutOfBoundsException,但我不知道它从哪里来。

该异常似乎也似乎不只喜欢整数值,字符串,双精度数,并且其他所有数据类型都可以。

该列表在main中没有设置长度,所以现在我不知道为什么Java会抱怨。

public E get(int i)
   {
      if (i < 0 || i >= size())
      {
         throw new IndexOutOfBoundsException("" + i);
      }
      else if (i == 0 )
      {
         return head.value;
      }
      return get(i, head);
   }

   private E get(int i, Node node)
   {
      if (i == 0)
      {
         return (E) node.value;
      }
      return (E) get(i - 1, node.next);
   }
java list linked-list indexoutofboundsexception
2个回答
0
投票
if (i < 0 || i > size() - 1)

您不想检查它何时相等,因为您需要size() - 1索引的值。另外我猜size()返回链表的大小,因此您必须对其进行调整:例如。 {1, 2, 3}的大小为3,但是第三个数字在索引2中。因此,您需要3 - 1


0
投票
if (i < 0 || i >= size())
{
   throw new IndexOutOfBoundsException("" + i);
}

我假设size()返回列表的大小。

错误是因为列表的长度从1开始。列表本身没有。例-{a,b,c}的长度是3但是,a为0,b为1,c为2

因此将需要减去1。

希望这对您有所帮助!随时对关注,问题或批评发表评论。

© www.soinside.com 2019 - 2024. All rights reserved.