我對Java相當陌生,試圖編寫一個算法,返回等於總數的對的索引總和。當調用遞歸函數時發生IndexOutOfBoundsException
當我打開關於邊界的遞歸函數時,出現錯誤。對我來說界限看起來很好,我只是通過更新的數組列表,因此我不知道它從哪裏來。
錯誤
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;
}
}
任何幫助深表感謝。
那它!我甚至在之前意識到這一點,並正在用不同的方法查看'list iterators'。謝謝,休息時間... – andrewgi