【问题标题】:Empty arrayList and empty string throws StringIndexOutOfBounds exception空 arrayList 和空字符串抛出 StringIndexOutOfBounds 异常
【发布时间】:2013-07-19 16:39:20
【问题描述】:

我在这部分代码中遇到 StringIndexOutOfBounds 异常。
捕获 myList 的字段在 UI 中是可选的。仅当 myList/myURL 字符串为空时才会出现此错误。我该如何处理?

有人可以纠正我在这里做错了什么吗?

    if (myList != null) {

            for (int r = 0; r < myList.size(); r++) {
                myURL = myURL + myList.toString() + ",";
            }

            myURL = myURL.substring(0, myrssURL.length() - 1);
            myURL = myURL.replace("[", "").replace("]", ""); 
        }
   else
    {
        rssList.clear();
        rssURL=null;
        System.out.println("inside else >>>>");
    }

【问题讨论】:

    标签: java string exception arraylist


    【解决方案1】:

    如果您的长度为 0,myURL = myURL.substring(0, myrssURL.length() - 1); 将评估为 myURL = myURL.substring(0,-1);,这是您遇到越界错误的地方。

    要修复,您应该检查arrayList.isEmpty() 或长度是否为0。

    【讨论】:

      【解决方案2】:

      检查是否有空?

      if (myList != null && !myList.isEmpty()) {
      
      // same code as before
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-02
        • 2012-09-09
        • 2015-09-25
        相关资源
        最近更新 更多