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 。