Java empty, null, blank still stupidly unclear?

When writing code, I often encounter situations where empty, null, and blank are judged. These concepts may seem similar, but they have different meanings and usages. This article will introduce the differences between these three concepts, and analyze how to make judgments in specific scenarios.

empty

Empty refers to a string whose length is 0/Java collection object does not have elements. You can use the isempty() method to determine whether a string is empty. You can also use the isEmpty() method to determine whether a Java collection element is empty.

For example:

public class Demo {

    public static void main(String[] args) {

        String str = "";

        if (str.isEmpty()) {

            System.out.println("This string is empty");

        }

    }

}

The above code will output "This string is empty" because the variable str is an empty string.

In addition, a common mistake is to think that a string containing spaces or multiple spaces is empty, which is incorrect. For example:

public class Demo {

    public static void main(String[] args) {

        String str = "  ";

        if (str.isEmpty()) {

            System.out.println("This string is empty");

        }

    }

}

The above code will not output anything, because the variable str is not an empty string, but a string containing two spaces.

null

null indicates that an object does not exist. If a reference variable is not initialized or is explicitly assigned a value of null, then the value of the variable is null. For example:

public class Demo {

    public static void main(String[] args) {

        String str = null;

        if (str == null) {

            System.out.println("This string is null");

        }

    }

}

The above code will output "This string is null" because the value of the variable str is null.

It should be noted that for basic data types (such as int, double, etc.), they cannot be assigned a value of null . If you try to assign a primitive data type to null, a compilation error will occur.

blank

Blank refers to a string whose length is greater than 0 but contains only spaces (including tabs and newlines). In Java, you can use the isblank() method to determine whether a string is blank. For example:

public class Demo {

    public static void main(String[] args) {

        String str = "  ";

        if (str.isBlank()) {

            System.out.println("This string is blank");

        }

    }

}

The above code will output "This string is blank" because the variable str contains two blanks, and this is the only content of this string.

It should be noted that there is no isblank() method before Java 11 . If you are using an earlier version of Java, you should use the trim() method to remove spaces from both ends of the string and check if the result is empty. For example:

public class Demo {

    public static void main(String[] args) {

        String str = "  ";

        if (str.trim().isEmpty()) {

            System.out.println("This string is blank");

        }

    }

}

The above code will also output "This string is blank", because the variable str becomes an empty string after being processed by the trim() method.

summary

The three concepts of empty, null and blank have obvious differences:

Empty means that a string has a length of 0, and there are no elements in the Java collection.

null indicates that an object does not exist;

blank means a string whose length is greater than 0 but contains only spaces.

To better understand these concepts and differences, here is some sample code.

public class Demo {
    public static void main(String[] args) {
        String emptyStr = "";
        String nullStr = null;
        String blankStr = "  ";

        // 判断empty字符串
        if (emptyStr.isEmpty()) {
            System.out.println("This string is empty");
        }

        // 判断null字符串
        if (nullStr == null) {
            System.out.println("This string is null");
        }

        // 判断blank字符串
        if (blankStr.isBlank()) { // 注意: Java 11之前是没有isblank()方法的
            System.out.println("This string is blank");
        }
    }
}

The above code will output "This string is empty" and "This string is blank" because the variable emptyStr is an empty string and the variable blankStr contains two spaces.

How to judge empty Java collection

List is empty

The isEmpty() method is a general method that can be used for all classes that implement the java.util.Collection interface (such as List, Set, etc.). Returns true if there are no elements in the collection; otherwise returns false.

import java.util.ArrayList;
import java.util.List;

public class Demo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        System.out.println(list.isEmpty()); // 输出 true

        list.add("apple");
        System.out.println(list.isEmpty()); // 输出 false
    }
}

The above code creates an empty ArrayList and checks whether it is empty using the isEmpty() method. Then an element is added to the list, which is checked again using the isEmpty() method. The first output is true because there are no elements in the list; the second output is false because there is one element in the list.

Map is empty

Map can be judged whether it is empty in the following ways:

1. Use the isEmpty() method: Map provides an isEmpty() method, which returns true if there is no mapping relationship in the Map.

import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        System.out.println(map.isEmpty()); // 输出 true

        map.put("key", "value");
        System.out.println(map.isEmpty()); // 输出 false
    }
}

 

2. Determine the size of the Map: Use the size() method to obtain the number of key-value pairs in the Map. If it is 0, it means the Map is empty.

import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        System.out.println(map.size() == 0); // 输出 true

        map.put("key", "value");
        System.out.println(map.size() == 0); // 输出 false
    }
}

 

3. Determine whether the key set in the Map is empty: use the keySet() method to obtain the set of all keys in the Map, and then determine whether the set is empty.

import java.util.HashMap;
import java.util.Map;

public class Demo {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        System.out.println(map.keySet().isEmpty()); // 输出 true

        map.put("key", "value");
        System.out.println(map.keySet().isEmpty()); // 输出 false
    }
}

It should be noted that the above three methods can all judge whether the Map is empty, but it is recommended to choose the most suitable method according to the actual situation. If you only need to know whether the Map is empty, use the isEmpty() method directly; if you need to perform other operations (such as traversal, deletion, etc.), you may need to obtain the size or key collection of the Map.

Guess you like

Origin blog.csdn.net/xijinno1/article/details/132123472