Reprinted from: www.cnblogs.com/wyq178/p/13…

preface

JDK as our daily essential call class library, which provides a large number of basic classes for us to use. It can be said that without JDK, our Java code can not go any further, JDK brings us convenience is countless, but at the same time these methods in the use of some pit, if you do not pay attention to it is easy to fall into the trap, causing the program to throw errors.

Many methods in the JDK do not make non-NULL judgments, and it is possible that the author of the JDK designed it by default and the developer already handled null values. However, this design can cause very serious consequences, it is a hidden danger.

For example, we found that an order was not refunded this morning. After a whole morning of searching, we found that the code was written by a colleague and no non-null judgment was made on the value of the BigDecimal method, resulting in a null pointer exception being thrown by the program. Therefore, a seemingly simple exception could not directly refund many orders. And to fix the refund issue, it takes a lot of time to fix, and the cost of getting it wrong is too high.

In this installment, we’ll take a look at some of the most common methods in the JDK that you’ve encountered.

1. Pitfalls of the string.valueof () method

Scene of the incident: one morning, we were happy to knock on the code, suddenly some customer complaints, we sent users a part of the message is respect “NULL” hello, XX and so on.

The development of the first time to see the code, feel there is no problem ah, why SMS content will appear user name null, is not through the non-null judgment? String.valueof () is a type conversion method provided by String. Let’s take a look at it:

// Call the user service to get user information based on the user ID
Map<String, Object> userInfo =
Copy the code

This code is simplified, and the main function is to obtain user information and send SMS messages according to user id through user service. Later, after locating, the problem is found: First, there are special emoji symbols in the user’s name, and some of them failed to be written to the database, because at that time

The database character format is not emoji-compatible, and the value is null due to this problem.

This is the big point, and the big catch, but notice that it returns a “null” string, not null. There is a big difference between the two. When a nonnull judgment is made, true is returned. That’s the “null” string that’s null-eligible!

The correct posture must be nulled before the string.valueof method:

The integer.parseint () method is very pretentious

Accident scene:

In one business scenario, when the order is pulled out and the order list record is printed, the financial personnel need to pull out the reconciliation, but they always find a very strange phenomenon that the data is less every time.

Fortunately, the financial found, or the third party financial reconciliation will lose a lot of money… Finally, it was found that there was an error in converting a field value of the order to Integer. The field value of the order was 120.0. Integer.parseint () directly reported an error Checked for a long time…) Know the truth we are a little embarrassed, so little bit of error investigation for a long time, it is not should ah.

The integer.parseint () method is used to convert a String to a method of type Integer. This method is narrow because it is a String parameter and has no limitation. When passing in data such as 50.0, 20L, 30d, 40f, etc.

Let’s look at a chestnut:

NumberFormatException will be thrown:

In fact, it can automatically convert such data as decimals, floating-point data, and long data, rather than giving us annoying error messages, and can be converted by Bigdecimal if we know in advance that it is an integer or decimal (note that this method does not work with double and float, long data, such as 10D) ,20L)

Floating-point, long-type data can be handled as follows:

The numberUtil.parseint () method of Hutool is recommended, which takes full account of the exception parsing problems caused by floating point, long, decimal and other types of data. Hutool is an open source tool class library.

3. Division pit of Bigdecimal is not negotiable

BigDecimal is known to be the most efficient data type for handling amounts, and it is generally used in financial statement calculations to prevent errors in amounts, while double and float are slightly off. You happily do a calculation with Bigdecimal, and the final result returns a problem. Let’s take a look at one:

The common division method works without any problems, no problems. But let’s see what happens if we use Bigdecimal to accept the parameters from the front end, which the user input is uncertain, once the data in the program is as follows:

Execution result a look, unexpectedly error ah:

This is the pit of BidDecimal, which throws a ArithmeticException once the result returned is an infinite repeating decimal. Therefore, when performing Bigdecimal division, it is necessary to preserve decimals.

4, collections.emptyList () This list is not that list

Let’s start with a sample:

public List<String> getUserNameList(String userId) {
    List<String> resultList = Collections.emptyList();
    try {
        resultList = userDao.getUserName(userId);
    } catch (Exception ex) {
        logger.info(ex);
    }
    return resultList;
}
Copy the code

. This will throw an error, the main problem is that the Collections emptyList () is not what we see at ordinary times the List, this List does not support the add and remove methods, otherwise it will be thrown operationNotSupportException:

Throws an exception:

The reason :Collections.emptyList doesn’t return the usual list, it’s an internal constant class:

public static final List EMPTY_LIST = new EmptyList<>();
Copy the code

This list does not have the ability to add or remove elements, which I suspect is because the JDK was designed to treat this list as a read-only list that does not provide the ability to write data, so it can only be returned as a null value and cannot be deleted or added.

5. Can you delete a list and traverse it at the same time?

The answer is yes. Otherwise, how can the list delete the data?

Unfortunately, double 叒 yi is wrong:

ModCount is an attribute in the list used to count the number of changes. When counting elements, the element is incremented by 1, while the element is incremented by l If the IST traverses and deletes, it will cause

Excepted is inconsistent with modCount, and an exception is thrown.

To avoid this problem, use iterator. remove to iterate over the delete.

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
    Integer integer = iterator.next();
    if (integer == 2) { iterator.remove(); }}Copy the code

6, summary

The JDK designers had two big characteristics:

① Most people do not make non-null judgments

② Throw a new Exception directly when an error occurs

In the actual development, the face of JDK must be careful to use, JDK provides convenience at the same time, there are also some of our use of the blind area, should develop read the source code, pay more attention to error processing, to prevent a big stumble in small problems.

Let’s go back to the problem of subtract method that I mentioned earlier. The user could not receive a refund until I had finished dealing with this problem, which resulted in a steep drop in user experience, and some users even called to complain. A colleague’s carelessness and carelessness have caused a lot of negative impact on the company. Although the technical problem is not big, the business impact is very serious. So we must prevent small problems, small problems have to be carefully polished, in order to avoid many problems.

Ps: The next part will be a little easier, and it will explain the problems or problems of using this method. This part will be updated continuously. Once I find the method of pit in my work, I will update it in time.

7. Keep updating

7.1 It is best to use compareTo instead of equals for Bigdecimal comparisons. In the following case, using equals overwrites Bigdecimal causes problems:

1 and 1.0 return false when comparing. This is because the equals source code compares the scale(i.e. accuracy) of the data and returns false if the data is inconsistent. This is not the case when using compareTo

7.2: mysql subtraction calculation if there is a null value result null

Select 5- NULL; null; ifNULL (field,0)

Proper posture:

7.3: the String of the split method on | | segmentation need to be escaped, otherwise the result will have a problem

Personal website

  • Github Pages
  • Gitee Pages