background
A simple list retrieval function. The list element has an attribute of type Long. A low-level error was made during the traversal process, causing the function flow to remain in error.
Two Long ==
When searching for the object corresponding to an element A in list B, query according to the element primary key. The primary key type is wrapper type Long. The traversal process is as follows:
For (MyData temp:b){if (temp.getid () == a.getId() {// MyData id attribute is Long return temp; }}Copy the code
Breakpoint debugging found that the problem was with the == operation. Change to equals.
A review of how Java Long’s wrapper type and element type are equal:
Long a = 81487354807713792L;
Long b = 81487354807713792L;
System.out.println(a==b); // false
System.out.println(a.equals(b)); // true
long c = 81487354807713792L;
long d = 81487354807713792L;
System.out.println(c==d); // true
Copy the code
An exception thrown by add on collections.empty_set
Another naive error is caused by adding collections.empty_set, which involves merging two Collections, the first of which, A, might be collections.empty_set, and eventually merging another collection, B, into A to get A large collection.
Set<MyData> a = getDatas(); // If null, collections.empty_set Set<MyData> b = getDatas1(); a.addAll(b);Copy the code
When set A is an empty object of the set, the operation is abnormal:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractCollection.add(AbstractCollection.java:262)
Copy the code
Fix: If you need to add a collection directly, you can’t use collections.empty_set.
Use considerations for the empty collection of Collections
In the case of collections.empty_set, which is defined with the following three lines of code:
public static final Set EMPTY_SET = new EmptySet<>();
private static class EmptySet<E> extends AbstractSet<E>
AbstractSet<E> extends AbstractCollection
Copy the code
At its core, AbstractCollection class add directly throws an exception by default, limiting empty collections from being added:
public boolean add(E e) {
throw new UnsupportedOperationException();
}
Copy the code
Conclusion: None of the EMPTY_XXX objects in the Java.util. Collections class can be added.
The revelation of
After locating these two silly mistakes, I remember the joke: write code in minutes and find bugs in two hours. These two problems happened to be part of a relatively complex process. It took about ten minutes to test the test environment, and the machine slowed down, and these two small problems took two hours.
Take this article as a record, so profound process, estimate later also won’t commit again!