Questions recently encountered with removeAll.

To analyze problems

Entity class

@Data
public class EntityVo extends Entity {

    .....
}
Copy the code

The Collection is used to delete contained elements

    collection.removeAll(arr);
Copy the code

As soon as the code executes, everything is deleted

First look at the API

boolean removeAll(Collection<? > c) Remove all elements of the specified collection from the list (optional operation).Copy the code

That’s right, remove the elements contained in the subset and look at the API, remove all elements contained in the subset, and notice the word contains! The removeAll method compares the collection elements first and removes them only if they are equal. As many of you already know, the removeAll method removes them because of equals.

The remove and removeAll methods are implemented in:

Java. Util. AbstractCollection specific code is:

public boolean removeAll(Collection<? > c) { boolean modified =false; Iterator<? > it = iterator();while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true; }}return modified;
}
Copy the code

Identify the cause of the problem

You can see that when you call the removeAll method, you are actually looping over the remove method, which contains a key piece of code: if (o.dice (it.next()))!

So, conclude that lombok@data! Is added to the above example entity class. EqualsAndHashCode does not call the equals method of the parent class.

@data is equivalent to @getter, @setter, @requiredargsConstructor, @toString, @equalSandHashCode. As you can see from the official documentation, when using the @data annotation, you have the @EqualSandHashCode annotation, and then you have equals(Object Other) and hashCode() methods in this class, and you don’t use the attributes of the parent class, which leads to possible problems.

For example, if you have multiple classes with the same partial attributes, and you define them in a parent class where the ID (database primary key) is also in the parent class, there will be objects that are not equal when compared, but are determined to be equal because lombok’s automatically generated equals(Object Other) and hashCode() methods. And that leads to errors.

The solution

Fixing this problem is simple:

  1. use@Getter @Setter @ToStringInstead of@DataAnd customize itequals(Object other)andhashCode()Method, such as some classes that just need to determine whether the primary key IDS are equal.
  2. Or use in use@DataAt the same time@EqualsAndHashCode(callSuper=true)Annotation.
@Data
+ @EqualsAndHashCode(callSuper=true)
public class Entity {

    .....
}
Copy the code