【问题标题】:indexOf error java.lang.ArrayIndexOutOfBoundsException exceptionindexOf 错误 java.lang.ArrayIndexOutOfBoundsException 异常
【发布时间】:2016-05-20 16:00:18
【问题描述】:

我有一个包含值的 ArrayList:

Lista
Lista2
Lista 3

当我使用时。

pCols.indexOf("Lista")) 没问题

pCols.indexOf("Lista2")) 没问题

pCols.indexOf("Lista 3")) 错误 java.lang.ArrayIndexOutOfBoundsException 异常

【问题讨论】:

  • 异常并非来自这段代码。我的猜测:在您的代码中的某处,找不到您的项目。在这种情况下,indexOf() 返回 -1,您最终会在列表的索引 -1 处搜索项目。
  • List.indexOf 不会抛出 ArrayIndexOutOfBoundsException
  • 我的错,“Lista 3”在最后一个字符“Lista 3”中有一个空格,对不起。

标签: java android arrays indexoutofboundsexception indexof


【解决方案1】:

根据您的评论,the "Lista 3" has a space in the last char "Lista 3 ",原因很明确:

在这种情况下,List.indexOf 将返回 -1。这不在数组的有效索引范围内,即 0, ..., n-1 - 是数组的长度。

供您参考:https://developer.android.com/reference/java/util/List.html#indexOf(java.lang.Object)

解决办法很明显:

pCols.indexOf("Lista 3 ".trim()))

trim() 将删除不需要的尾随空格。
供您参考:https://developer.android.com/reference/java/lang/String.html#trim()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-29
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多