Java 返回子列表中的第一项(如果有),如果为空,则返回null
到目前为止,我发现indexOutOfBoundsException错误Java 返回子列表中的第一项(如果有),如果为空,则返回null,java,arraylist,Java,Arraylist,到目前为止,我发现indexOutOfBoundsException错误 公共静态整数FirstSubList(ArrayList列表){ if(list==null | | list.isEmpty()){ 返回null; } 返回列表。获取(0)。获取(0); } 您需要在列表中添加检查。获取(0) 您缺少一项检查,以确保list.get(0)返回的列表不是null或空: public static Integer firstSubListItem(ArrayList<ArrayLi
公共静态整数FirstSubList(ArrayList列表){
if(list==null | | list.isEmpty()){
返回null;
}
返回列表。获取(0)。获取(0);
}
您需要在列表中添加检查。获取(0)
您缺少一项检查,以确保
list.get(0)
返回的列表不是null
或空:
public static Integer firstSubListItem(ArrayList<ArrayList<Integer>> list) {
if (list == null || list.isEmpty()) {
return null;
}
List<Integer> list0 = list.get(0);
if (list0 == null || list0.isEmpty()) {
return null;
}
return list0.get(0);
}
公共静态整数FirstSubList(ArrayList列表){
if(list==null | | list.isEmpty()){
返回null;
}
List list0=List.get(0);
if(list0==null | | list0.isEmpty()){
返回null;
}
返回list0.get(0);
}
您需要检查list.get(0)
是否为null或为空。仅仅因为外部列表不是空的并不意味着它包含的元素都是至少有1个元素的列表。哦,是的,现在知道了,非常感谢
public static Integer firstSubListItem(List<List<Integer>> list) {
if (list == null || list.isEmpty() || list.get(0).isEmpty()) {
return null;
}
return list.get(0).get(0);
}
System.out.println(firstSubListItem(Arrays.asList())); // null
System.out.println(firstSubListItem(Arrays.asList(Arrays.asList()))); // null
System.out.println(firstSubListItem(Arrays.asList(Arrays.asList(1, 2)))); // 1
public static Integer firstSubListItem(ArrayList<ArrayList<Integer>> list) {
if (list == null || list.isEmpty()) {
return null;
}
List<Integer> list0 = list.get(0);
if (list0 == null || list0.isEmpty()) {
return null;
}
return list0.get(0);
}