NPE effective way of solving

Determining whether two objects are equal

Objects.equals(a,b)

Automatic Analyzing equal unboxing

Objects.equals(0,Integer)

Determining whether the string is empty

StringUtils.isBlank(str)

Determining whether the set is empty

CollectionUtils.isEmpty(collection)

to sum up

1. Awareness: Using obj.doSomething (remember when the judge)  obj = null! . Awareness of the need to develop a long process, we can help by tool, IDEA is a very good tool.

2. determining whether objects are equal, using  Objects.equals (A, B)  , of course Objects  tools provided also close to our  toString  and  requireNonNull  such good helper 

3.  trap automatic unpacking . When using the wrapper classes and primitive types do comparison, paying particular attention to the issue null pointer

 

4. Check the string is empty, using commons-lang3  package  isEmpty method and isBlank StringUtils provided  . In addition,  lowerCase and upperCase  string conversions case conversion, a null pointer can be avoided 

 

5. commons-collections  package  CollectionUtils.isEmpty method to check whether the set is empty  

 

6. If desired interface returns a collection returns empty, the empty set is returned and not null . But each time a new set of new, can affect the performance and unnecessary object creation, use  Collections.emptyList ();  to return the empty set globally shared immutable

 

7. Optional Java8 is introduced to solve the NPE weapon, when it combines with Lambda expressions can be very powerful .

Guess you like

Origin www.cnblogs.com/siran/p/11280526.html