Detailed Explanation of the Method to Judge whether an Object is Empty in Java

  • 2021-07-22 09:52:36
  • OfStack

First, let's look at the judgment method of tool StringUtils under 1:

One is under org. apache. commons. lang3 package;

The other one is under org. springframework. util package. There is a gap between these two StringUtils tool classes in judging whether an object is empty:


StringUtils.isEmpty(CharSequence cs); //org.apache.commons.lang3 Under the bag StringUtils Class, the method parameter to determine whether it is empty is a character sequence class, that is, String Type 

StringUtils.isEmpty(Object str); // And org.springframework.util The parameters under the package are Object Class, that is, it can not only judge String Type, you can also judge other types, such as Long And other types. 

From the above example, we can see that the second StringUtils class is more practical.

Let's look at the source code of StringUtils. isEmpty (CharSequence cs) of org. apache. commons. lang3:


public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}

Next is StringUtils. isEmpty (Object str) source code of org. springframework. util:


public static boolean isEmpty(Object str) {
    return (str == null || "".equals(str));
}

Basically, the method StringUtils. isEmpty (Object str) can be used to judge whether the object is empty or not.

The next step is to determine whether the array is empty


list.isEmpty(); // Return boolean Type. 

Determine whether the set is empty

Example 1: Determine whether the set is empty:


CollectionUtils.isEmpty(null): true
CollectionUtils.isEmpty(new ArrayList()): true
CollectionUtils.isEmpty({a,b}): false

Example 2: Determine whether the set is not empty:


CollectionUtils.isNotEmpty(null): false
CollectionUtils.isNotEmpty(new ArrayList()): false
CollectionUtils.isNotEmpty({a,b}): true

Actions between 2 collections:
Set a: {1, 2, 3, 3, 4, 5}
Set b: {3, 4, 4, 5, 6, 7}


CollectionUtils.union(a, b)( Union ): {1,2,3,3,4,4,5,6,7}
CollectionUtils.intersection(a, b)( Intersection ): {3,4,5}
CollectionUtils.disjunction(a, b)( Complement set of intersection ): {1,2,3,4,6,7}
CollectionUtils.disjunction(b, a)( Complement set of intersection ): {1,2,3,4,6,7}
CollectionUtils.subtract(a, b)(A And B Difference of ): {1,2,3}
CollectionUtils.subtract(b, a)(B And A Difference of ): {4,6,7}

Related articles: