[英]Casting iterator to Integer - ConcurrentModificationException
I am trying to find the second biggest element in a list using recursion and an Iteration: 我试图使用递归和迭代在列表中找到第二大元素:
static List<Integer> list = new ArrayList<Integer>();
static Iterator<Integer> it = list.iterator();
public static int secondBiggest(List<Integer> a) {
if(it.hasNext()) {
Integer cur = it.next();
if (cur > biggest) {
secondBiggest = biggest;
biggest = cur;
} else if (cur < biggest && cur > secondBiggest) {
secondBiggest = cur;
}
secondBiggest(a);
}
return secondBiggest;
}
What I get is a 我得到的是
ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.base/java.util.ArrayList$Itr.next(Unknown Source)
java.base / java.util.ArrayList $ Itr.checkForComodification上的ConcurrentModificationException(未知源)java.base / java.util.ArrayList $ Itr.next上的(未知源)
in line 6 in the code previously mentioned 在前面提到的代码的第6行中
The exit for recursion is not right, it can't get to the end: if(it.hasNext()) 递归出口不正确,它无法到达终点:if(it.hasNext())
If you really want to implement by recursion, You can use the following example: 如果您确实要通过递归实现,则可以使用以下示例:
public void test() {
List<Integer> integers = Arrays.asList(1, 4, 1234, 5, 6, 77);
int secondBiggest = second(integers, -1, 0, 0);
System.out.println(secondBiggest);
}
public Integer second(List<Integer> a, Integer biggest, Integer secondBiggest, Integer length) {
if (a.size() > length) {
Integer cur = a.get(length);
length++;
if (cur > biggest) {
secondBiggest = biggest;
biggest = cur;
} else if (cur < biggest && cur > secondBiggest) {
secondBiggest = cur;
}
secondBiggest = second(a, biggest, secondBiggest, length);
}
return secondBiggest;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.