public static boolean isComponentBefore(GuiInterface component) {
int index = 0;
for (int i = 0; i < components.size(); i++) {
if (components.get(i).getName() == component.getName()) {
if(components.get(i- 1) == null){
return false;
}
}
}
return true;
}
我目前使用这个,尽管这可能会导致 ConcurrentModificationExceptions 并且它不起作用,因为每当我尝试查看传入元素之前的元素是否为 null 时,它都会不断抛出 ConcurrentModificationExceptions。
我想知道是否还有其他方法可以做到这一点。
最佳答案
查看您的逻辑,如果 ArrayList
中给定组件之前的组件为 null
,您将出现 NullPointerException
,因为 Components.get(i)
将为 null
并且 components.get(i).getName()
将抛出 NPE。
你可以尝试稍微改变一下这里的逻辑。对于列表中的每个空元素,检查下一个组件是否是您正在搜索的组件并相应地返回。
for (int i = 0; i < components.size(); i++) {
if (components.get(i) == null) { // If a particular element is null, check if the next element is what you want
if(components.get(i+1).getName().equals(component.getName())) { // you need to handle the edge case for i+1 as well for the last iteration
return false;
}
}
}
请注意,您需要使用 equals()
方法而不是 ==
运算符来比较字符串。您还需要处理最后一次迭代的 i+1
极端情况。
关于Java:获取ArrayList中指定元素之前是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24645462/