1
public class App {
    public static void main(String[] args) {
   
    List<Pair<String, String>> SubPartandMaster = new ArrayList<Pair<String, String>>();
        

    List<String> wtpmList = new ArrayList<String>();
    wtpmList.add("1");
    wtpmList.add("2");
    wtpmList.add("3");
    wtpmList.add("4");
    wtpmList.add("5");
   
    List<String> wtpList = new ArrayList<String>();
    wtpList.add("a");
    wtpList.add("b");
    wtpList.add("c");

    System.out.println(wtpmList);
    System.out.println(wtpList);
    for (int i = 0; i < wtpmList.size(); i++) {
        SubPartandMaster.add(new Pair<String, String>(wtpmList.get(i), wtpList.get(i)));
    }

    }
}

我知道第二个列表没有更多的值,但我想null在这种情况下存储。例如

[(1,a),(2,b),(3,c),(4,null),(5,null)]

而不是这个,我得到错误

[1, 2, 3, 4, 5]
[a, b, c]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
        at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
        at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
        at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
        at java.base/java.util.Objects.checkIndex(Objects.java:359)
        at java.base/java.util.ArrayList.get(ArrayList.java:427)
        at App.main(App.java:28)

我知道原因,因为我无法从 wtpList 中检索更多内容,因为它有 3 个元素。但是如果值不存在,我可以存储 null 。

4

2 回答 2

2

您遍历两个不同大小的列表:

for (int i = 0; i < wtpmList.size(); i++) {
    SubPartandMaster.add(new Pair<String, String>(wtpmList.get(i), wtpList.get(i)));
}

一个有五个元素,其他三个。这导致java.lang.IndexOutOfBoundsException 尽快i=3

我知道第二个列表没有更多值,但在这种情况下我想存储 null 。例如

假设 wtpmList 总是大于(或等于)wtpList,您可以简单地先遍历最小的列表:

for (int i = 0; i < wtpList.size(); i++) {
    SubPartandMaster.add(new Pair<String, String>(wtpmList.get(i), wtpList.get(i)));
}

并在之后添加空值:

for (int i = wtpList.size(); i < wtpmList.size(); i++) {
    SubPartandMaster.add(new Pair<String, String>(wtpmList.get(i), null));
}

不对列表做任何假设,那么您必须更改代码以涵盖所有情况。

  int biggest_list = Math.max(wtpmList.size(), wtpList.size());
  for (int i = 0; i < biggest_list; i++) {
       if(i >= wtpmList.size())
          SubPartandMaster.add(new Pair<String, String>(null, wtpList.get(i)));
       else if (i >= wtpList.size())
          SubPartandMaster.add(new Pair<String, String>(wtpmList.get(i), null));
       else
          SubPartandMaster.add(new Pair<String, String>(wtpmList.get(i), wtpList.get(i)));
    }
于 2021-01-04T15:45:19.640 回答
0

如果不存在任何元素,您可以覆盖get它以使其工作poll并返回 null 值:

List<String> wtpList = new ArrayList<String>() {
  @Override
  public String get( int idx ) {
    return( idx < size() ? super.get( idx ) : null );
  }
};
于 2021-01-04T16:24:45.900 回答