-1

我是 Java 新手,我一直在尝试解决一个多星期以来的一个练习,我不知道我做错了什么。

我需要删除 ArrayList 的最后一个元素,在这种情况下是一个整数。

问题是当我运行测试时,它仍然返回旧值。

public static void removeLastOccurrence(int x, ArrayList<Integer> list) {
    if (list != null && !list.isEmpty()) {
       list.remove(list.size()-1);
    }
}

我也尝试使用list.remove(list.lastIndexOf(x));

但是当我运行这个测试时它仍然返回相同的列表。

public class UTest{
    @Test
    public void testMultipleLast() {
        ArrayList<Integer> input = new ArrayList<Integer>(asList(1,1,3,5,7,1,5,9,1));
        ArrayList<Integer> result = new ArrayList<Integer>(asList(1,1,3,5,7,1,5,9));
        Solution.removeLastOccurence(1, input);
        assertEquals(result, input);
    }
}

如果有人可以帮助并告诉我我缺少什么会很​​好,因为它变得非常令人沮丧,因为我觉得我只是缺少一小部分拼图。

4

5 回答 5

2

您的测试应该如下所示。在原始帖子的测试代码中,您实际上并没有调用您尝试测试的方法。

public class UTest
{
  @Test
  public void testMultipleLast() {
     ArrayList<Integer> input = new ArrayList<Integer>(asList(1,1,3,5,7,1,5,9,1));
     ArrayList<Integer> result = new ArrayList<Integer>(asList(1,1,3,5,7,1,5,9));

     // int x = ?
     ArrayList<Integer> actual = SomeClass.removeLastOccurrence(x, input)
     assertEquals(result, actual);
  }
 }

removeLastOccurrence()方法可以执行以下操作

if(list != null && !list.isEmpty()){
    list.remove(list.size() - 1);
}
于 2017-03-08T19:02:03.330 回答
1

你必须使用:

list.remove(list.size()-1);

并返回您的新列表,以便您可以使用:

public static ArrayList<Integer> removeLastOccurrence(int x, ArrayList<Integer> list) {
    if (list != null && !list.isEmpty()) {
       list.remove(list.size()-1);
    }
    return list;
}
于 2017-03-08T18:59:28.300 回答
1

这是因为您没有删除任何元素。

list.get(list.size()-1);

不删除元素。

利用

list.remove(list.size()-1)

反而。

于 2017-03-08T18:59:43.747 回答
1

根据Java ArrayList API with method,您只需获取ArrayList 中位置get(int index)的元素。index这是您正在寻找的方法:

public static void removeLastOccurrence(int x, ArrayList<Integer> list) {
    if (list != null && !list.isEmpty()) {
        list.remove(list.size()-1);
    }
}
于 2017-03-08T19:01:49.467 回答
-1

如果您将列表作为参数传递给方法,它将成为局部变量。因此,您不会从input列表中删除元素,而只是从局部变量中删除list。解决方案是使用相同的代码return从您的方法中获取本地列表,或者remove直接从“输入”列表中获取元素。原始方法中的 x 参数是不必要的。

于 2018-01-05T19:19:55.100 回答