简体   繁体   中英

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 :

true if this list contained the specified element

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.

( 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)) )

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):

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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