【问题标题】:java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 exception [duplicate]java.lang.IndexOutOfBoundsException:索引:0,大小:0异常[重复]
【发布时间】:2016-12-28 20:57:33
【问题描述】:

我收到错误 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0。

public Collection<AdDistribution> getAdDistribution(byte srch, byte cont) throws IndexOutOfBoundsException {

    List<AdDistribution> mediums = new ArrayList<>();
    List<AdDistribution> adDistribution = new ArrayList<>();
            adDistribution.add(AdDistribution.SEARCH);
            adDistribution.add(AdDistribution.CONTENT);
            if (adDistribution.isEmpty()) {
                return null;
              }

    if (srch == 0 && cont == 0) {
        mediums = new ArrayList<>();
        mediums.set(0, adDistribution.get(0));
    }
    if (srch == 1 || cont == 1) {
        mediums = new ArrayList<>();
        if (srch == 1) {
            mediums.set(0, adDistribution.get(0));
        } else if (cont == 1) {
            mediums.set(0, adDistribution.get(1));
        }
    }
    if (srch == 1 && cont == 1) {
        mediums = new ArrayList<>();
        mediums.set(0, adDistribution.get(0));
        mediums.set(1, adDistribution.get(1));
    }
            return mediums;
}

【问题讨论】:

    标签: java indexoutofboundsexception


    【解决方案1】:

    问题是您正在使用 set 方法更新索引 0 处的元素

    set(index,value) 方法需要一个元素出现在该索引处

    但在此之前,您还没有在 medium arraylist 中的该位置添加任何元素。

    所以你需要先在索引 0 处添加一个元素,然后你才能使用 set 方法更新它

    【讨论】:

      【解决方案2】:

      你需要使用

      mediums.add(adDistribution.get(0));
      

      而不是mediums.set(0, adDistribution.get(0));

      ArrayList.set(int, Object) 要求有要替换的元素:

      用指定元素替换此列表中指定位置的元素。

      抛出: IndexOutOfBoundsException - 如果索引超出范围 (index = size())

      在新列表中,size() == 0,所以set(0, something) 失败。

      【讨论】:

      • 可以分享修改后的代码吗
      • 在我的回答中:“您需要使用 [修改后的代码] 而不是 [您的代码]”。对不起,这就是你从我这里得到的一切:你需要自己付出一些努力。
      【解决方案3】:

      编辑: 我只是删除了不必要的 if 语句并简化了它们以使您的代码更具可读性。
      然后我将 set 函数替换为 add 函数,因为 set 只能设置现有元素。

      EDIT2:根据 Andy Turner 的回答,我修改了我的代码。谢谢你的建议!

      经过这些修改后,代码应如下所示(根据需要添加/删除/修改):

      public Collection<AdDistribution> getAdDistribution(byte srch, byte cont) throws IndexOutOfBoundsException {
      
          List<AdDistribution> mediums = new ArrayList<>();
      
          if( ( srch == 0 && cont == 0 ) || srch == 1 ) {
              mediums.add(AdDistribution.SEARCH);
          }
      
          if( cont == 1 ) {
              mediums.add(AdDistribution.CONTENT);
          }
      
          return mediums;
      }
      

      【讨论】:

      • “我刚刚删除了不必要的 if 语句”您也可以删除 if (adDistribution.isEmpty()) {,这绝不是错误的。 adDistribution 也是多余的:只需将AdDistribution.SEARCHAdDistribution.CONTENT 直接添加到mediums
      • 感谢您的建议。起初我没有注意那些代码部分,我应该对所有事情都更准确。我已经编辑了我的评论。问候!
      猜你喜欢
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多