-1

I am supposed to write a recursive method that deletes a reoccurrence of a number at the end of an arrayList. I feel like I've covered my bases with every possible error but I get an out of bounds error once it processes for the 3rd time. I can't seem to figure out why I get the out of bounds error. Seems like all of my counts are staying in the right positions, and I have an if-statement that uses recursion once the counter positions are equal, which is where I figured the error message would be.

Any insight would be helpful, need to learn from my mistakes. Recursion is not my strong-suit either.

EDIT: This is the list; [100, 200, 200, 300, 400, 300, 100, 500, 500, 400, 100, 400, 100, 100]

public static void deleteDuplicateValues(ArrayList<Integer> list, int decreasingCounter, int searchingVal, int outsideCounter)
  {
    int searchingValue = list.get(searchingVal);


    if (outsideCounter < (list.size()-1))
    {

      if (searchingValue == list.get(list.size()-1-decreasingCounter)) //finds
      {
        System.out.print (searchingValue + "   FOUND at position" + (list.size()-1-decreasingCounter) + "\n");
        list.remove(list.size()-1-decreasingCounter);

        deleteDuplicateValues(list, decreasingCounter,searchingVal+1, outsideCounter+1);

      }
      else
      {
        if (list.size()-1-decreasingCounter == outsideCounter) //gets to end without finding double
        {//After searching x amount of times, they will equal eachother if not found.
          //outsideCounter only increments when found or end of processing. 
          decreasingCounter = 0;
          deleteDuplicateValues(list, decreasingCounter,searchingVal+1, outsideCounter+1); //goes to next position
        }

        else 
        {
          System.out.print("executed");
          deleteDuplicateValues(list, decreasingCounter+1, searchingVal, outsideCounter); //values UP1


        }
      }
    }
4

2 回答 2

0

您可以简化不变量。方法参数中只需要一个整数列表和要删除的数字的值,只有两个参数。我不明白你为什么需要所有其他人 - 尝试简化它,你会破解它。

于 2013-11-14T17:26:54.670 回答
0

我误会了你还是你想删除重复项?如果是这样,为什么不使用 java.util.Set 的任何实现?

Set<Integer> set = new HashSet<Integer>(list);
list.clear();
list.addAll(set);

我无法完全理解索引和计数的全部内容

编辑:我想我明白了。当你得到这个 if 语句时

if (searchingValue == list.get(list.size() - 1 - decreasingCounter)) {
    System.out.print(searchingValue + "   FOUND at position" + (list.size() - 1 - decreasingCounter) + "\n");
    list.remove(list.size() - 1 - decreasingCounter);

    deleteDuplicateValues(list, decreasingCounter, searchingVal + 1, outsideCounter + 1); <<-- HERE!
}

您删除了一个元素,即便如此,当您进行递归调用时,您增加了 serachingValue,但是,您已经通过删除元素移动了。我说清楚了吗?

于 2013-11-14T17:24:36.883 回答