preface

I almost got fired for changing haseMap to currenHaseMap in the project.

Judgment is equal

String equality
String str1 = null; String str2 = "java"; // str1.equals(str2); Error str2.equals(str1); Objects.equals(str1, str2); // use the jdkUtil utility class stringutils. equals(str1,str2); // Customize the tool classCopy the code
  • So to determine the equality of strings we have to make sure that the constant comes first.
  • Use the UTIl helper class (Objects) provided by the JDK.
  • Custom tool class, for null processing.
The wrapper class determines equality
Integer n1 = 100; Integer n2 = 100; System.out.println(n1 == n2); //true System.out.println(n1.equals(n2)); //true Integer n3 = 200; Integer n4 = 200; System.out.println(n3 == n4); //false System.out.println(n3.equals(n4)); //trueCopy the code

Why is n3== n4 false? Because of the caching mechanism of the wrapper class. Wrapper classes are compared using Equals. The best way to do this is to use utility classes. For example, if n3=null, n3.equals(n4) will raise nPE. This is not the case with utility classes. In short, to determine equality, if you don’t want to nullify (lazy, bad code), use utility classes. Proper use of utility classes can reduce unnecessary NPE in your code.

Ternary operator

This common pit is an NPE anomaly caused by automatic unpacking. This Alibaba development manual (need this manual can find me V: RXH8515) said very clear.

BigDecimal

Disallow initialization of floating-point numbers double,float
Double d = 1.001; Float f = 1.001 f; BigDecimal bigDecimal1 = new BigDecimal(d); BigDecimal bigDecimal2 = new BigDecimal(f); System.out.println(bigDecimal1); System.out.println(bigDecimal2);Copy the code

The output

1.000999999999999889865875957184471189975738525390625
1.00100004673004150390625
Copy the code

This result is not a bit different from the 1.001 we expected.

Floats and doubles can be used in engineering and scientific computations, where there is a loss of precision due to the structure of floating-point computations, but in the financial world precision problems can mean serious real-world economic losses, so the normal numeric types are not used in this scenario.

So never use floats and doubles for calculations involving money. Use BigDecimal and be sure to construct it with strings. In the example above we can initialize New BigDecimal(“1.001”) like this.

The decimal place must be reserved for division
        BigDecimal a = new BigDecimal("1");
        System.out.println(a.divide(new BigDecimal(3)));
Copy the code

The output

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
    at java.math.BigDecimal.divide(BigDecimal.java:1690)
    at com.workit.demo.antisper.Test.main(Test.java:11)
Copy the code

Workaround: Use the following two functions to set the accuracy

  • divide(num, scale)

  • divide(num, scale, roundingMode)

        BigDecimal a = new BigDecimal("1");
        System.out.println(a.divide(new BigDecimal(3), 2,BigDecimal.ROUND_HALF_UP));
    Copy the code

String separation (don’t forget to escape)

        String str = "java|php|c++";
        String[] split = str.split("|");
        for(String s:split){
            System.out.println(s);
        }
Copy the code

The output

j
a
v
a
|
p
h
p
|
c
+
+
Copy the code

The results were not what we expected, Java, PHP, c++. Solution to escape the | we split, code instead of String [] the split = STR. The split (” | “); And that’s right. String String of the split method need to escape: $| () [{^? * + \ a total of 12 special characters, meet with these characters segmentation String, need to add double backslash before these special characters \ \.

Arrays.aslist needs to be used with caution

Here are some common uses that don’t give us the results we expect.

Take an array of primitive types as an argument to asList
Int [] array = {1, 2, 3}; List list = Arrays.asList(array); System.out.println(list.size()); / / 1Copy the code

The output is 1 instead of 3 oh, is that a little different than expected? ArrayList treats int[] array as a generic object because the arguments to array.arrayList are variable-length generics, and primitive types cannot be genericized, so there is only one element array in the collection.

After taking an array as an asList argument, modify the array or List
String[] array = {" happy "," close "," Java "}; List list = Arrays.asList(array); Array [0] =" modify the first element of array "; List. Set (2," modify set element 3 "); System.out.println(Arrays.toString(array)); System.out.println(list.toString());Copy the code

The output

Modify the first element of array, close, modify the third element of array.Copy the code

Is it different from what we expected? Changed the value of the array to affect the value of the collection. The reasons are as follows: Because the collection elements generated by asList are directly referenced as the array as parameters, when the external array or collection changes, the array and the collection will change synchronously, which may cause inexplicable problems in normal coding.

After an array is converted to a collection, elements are added and deleted.
String[] array = {" happy "," close "," Java "}; List list = Arrays.asList(array); list.add("java"); System.out.println(list.toString());Copy the code

Output result:

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
Copy the code

The asList collection does not override methods like add,remove, etc., so it calls a method of its AbstractList parent that throws an exception. Use caution when using Arrays. AsList generated collections. ArrayList = new ArrayList(array.asList (array)); To use it.

CurrenHaseMap Notice the null values of key and value
String key = "java"; Map<String,Object> map = new ConcurrentHashMap<>(); map.put("1","2"); map.put(key,null); // Exception in thread "main" java.lang.NullPointerExceptionCopy the code

I remember that when I first started working, a management system I was in charge of had a cache of provinces, which was saved by HashMap. If you need to use the HashMap, you can fetch the province information directly from the HashMap. And then I backhand change it to currenHaseMap. The test environment tests fine, and then goes live with the rest of the functionality. After finishing the line, I did not return to this piece of content about the province, and then I went off work. The second day to go to work to reflect the province information of some registered users did not. The leader asked me whether I had changed the code of the province yesterday. I said I had changed a currenHaseMap. The leader will first make the code that was launched yesterday go back, and the province information will be available once the code is returned. Later, after careful investigation, there was an empty province information in the production database. The currenHaseMap is then loaded with the empty province information, and the currenHaseMap is not loaded after this empty record. Fortunately, the Intranet management system did not cause too much impact.

string.valueof

    String  userName= String.valueOf(parmMap.get("userName"));
        if(StringUtils.isNotBlank(userName)) {
            sql.append(" and tt.userName like %").append(userName);
        }
Copy the code

If parmap. get(“userName”) is null, then userName is “null”, which is a null string. As a result, data will be concatenated into SQL, and the export fails. Why this is so we look at the source code to see.

 public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
Copy the code

So when converting strings, we have to choose the appropriate method according to the actual situation.

conclusion

This article lists some common things about Java that you might miss if you didn’t notice. There are more points that need to be noted and you are welcome to add. In fact, these common pit basically as long as look at the source can be avoided.