[英]IndexOutOfBoundsException when calling recursive function
我對 Java 相當陌生,並試圖編寫一個算法來返回等於總數的對索引的總和。
當我點擊關於邊界的遞歸函數時出現錯誤。 邊界對我來說似乎很好,我只是傳入更新的數組列表,所以我不知道它來自哪里。
錯誤
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at com.example.helloworld.HelloWorld.getMatches(HelloWorld.java:36)
at com.example.helloworld.HelloWorld.getMatches(HelloWorld.java:41)
算法
public class HelloWorld {
ArrayList<Integer> matches = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
public static void main(String[] args) {
ArrayList<Integer> param = new ArrayList<>(Arrays.asList(0, 0, 0, 0, 1, 1));
int res = new HelloWorld().pairwise(param, 1);
System.out.println(res);
}
private int pairwise(ArrayList<Integer> arr, Integer total) {
for (Integer item: arr) {
this.temp.add(item);
}
getMatches(this.temp, total);
return getIndices(this.matches, arr);
}
private void getMatches(ArrayList<Integer> arr, Integer total) {
boolean noMatch = true;
for (int i=1; i<arr.size(); i++) {
if (arr.get(0) + arr.get(i) == total) {
//add to matches
this.matches.add(arr.get(0));
this.matches.add(arr.get(i));
//remove from temp
this.temp.remove(0);
this.temp.remove(arr.get(i));
noMatch = false;
if (this.temp.size() > 1) {
//ERROR HERE
getMatches(this.temp, total);
}
}
}
if (noMatch) {
this.temp.remove(0); //remove first one
if (this.temp.size() > 1) {
getMatches(this.temp, total);
}
}
}
private int getIndices(ArrayList<Integer> matches, ArrayList<Integer> array) {
int count = 0;
for (Integer item: matches) {
int index = array.indexOf(item);
count += index;
array.set(index, -3000);
}
return count;
}
}
任何幫助深表感謝。
呃......你正在從你正在迭代的數組中刪除元素......
這里:
for (int i=1; i<arr.size(); i++) {
//...code
}
您正在循環訪問數組的初始大小,即 6。然后在for 循環體內部從循環訪問的數組中刪除元素:
//remove from temp
this.temp.remove(0);
this.temp.remove(arr.get(i));
每次迭代都會使數組變短,這就是為什么會出現越界異常的原因。
你會想要復制你傳遞給getMatches
的數組,即
getMatches(new ArrayList<>(this.temp), total);
這樣,您將從temp
刪除元素,但不會影響您實際迭代的數組: arr
您必須刪除i
元素,然后刪除0
:
//remove from temp
this.temp.remove(arr.get(i));
this.temp.remove(0);
在 for 條件中添加 -1
private void getMatches(ArrayList<Integer> arr, Integer total) {
boolean noMatch = true;
for (int i=1; i<arr.size()-1; i++) {
if (arr.get(0) + arr.get(i) == total) {
//add to matches
this.matches.add(arr.get(0));
this.matches.add(arr.get(i));
//remove from temp
this.temp.remove(0);
this.temp.remove(arr.get(i));
noMatch = false;
if (this.temp.size() > 1) {
//ERROR HERE
getMatches(this.temp, total);
}
}
}
if (noMatch) {
this.temp.remove(0); //remove first one
if (this.temp.size() > 1) {
getMatches(this.temp, total);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.