简体   繁体   English

在Java中删除arraylist中的项目时如何打印

[英]How to print when item in arraylist is removed in java

I'm basically looking for some sort of either line of code or loop that I could use to just print text whenever an item of an array list is removed or haven't been able to find an answer. 我基本上是在寻找某种形式的代码行或循环,以便在数组列表中的某个项目被删除或无法找到答案时仅用于打印文本。

while (arraylist.remove()=true)
{
    //text
}

Obviously this code won't work but that's the idea I'm trying to go with. 显然,此代码无法正常工作,但这就是我要尝试的想法。

Any help is appreciated! 任何帮助表示赞赏!

First of all, that code snippet is already one way: when your code invokes the remove() method, then you can check the result of that operation - from its javadoc : 首先,该代码段已经是一种方法:当您的代码调用remove()方法时,您可以从该操作的javadoc中检查该操作的结果:

true if this list contained the specified element 如果此列表包含指定的元素,则为true

Of course, if you want to "understand" during remove that something is removed, you are always free to implement the List interface yourself, or to extend say AbstractList and add code to the various remove() methods. 当然,如果要在删除过程中“理解”要删除的内容,则始终可以自己实现 List接口,也可以扩展说AbstractList并将代码添加到各种remove()方法中。

( and just to be precise: the only reason your example code doesn't work is that you are doing remove() = true but should be using == true - or even better if (someList.remove(someObj)) ) (准确地说:您的示例代码不起作用的唯一原因是您正在执行remove() = true但应使用== true if (someList.remove(someObj))甚至if (someList.remove(someObj))效果更好)

You can add the following method to your class (you pass list containing an object and object itself as arguments). 您可以在类中添加以下方法(传递包含对象和对象本身作为参数的列表)。 After that you do the proper check (note that to check if the variable stores true you should use == instead of = , as the second one is an assignment operator): 之后,您要进行适当的检查(请注意,要检查变量是否存储true,应使用==而不是= ,因为第二个是赋值运算符):

public static <T> boolean removeAndPrint(List<T> list, T elem) {
    boolean result = list.remove(elem);
    if (result == true) {
        System.out.println("Item removed");
    } 
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM