Hello, I am silent king 2, a and Huang Jiaju the same height, and Andy Lau the same appearance level programmer. Ever since I started writing my first line of Java code 10 years ago, NULL has always been a special thing in Java. It is a good friend of null variables that are not needed to free up memory and improve performance. It’s also the enemy, because it’s associated with the well-known and annoying NullPointerException (NPE), which creator Tony Hoare admitted in 2009: “Null References is a ridiculous design, as if I lost a billion dollars on a bet”.

You see, Null turns out to be a frenemy.

Usually, the first thing we want to do to indicate that an element in a list doesn’t exist is return null, which is so reasonable that it can’t be refuted. To simulate a real application scenario, assume that The second party now wants to get a list of names from the database and print the names to the console as follows.

public class NullDemo {

    public static void main(String[] args) {

        List<String> names = getNamesFromDB();

        if(names ! =null) {

            for (String name : names) {

                System.out.println(name);

            }

        }

    }



    public static List<String> getNamesFromDB(a) {

        // The impersonator does not get the corresponding name from the database at this time.

        return null;

    }

}

Copy the code

Since the getNamesFromDB() method returns null as an indication that the list has no names, this means that the list must be nulled before traversing it, otherwise an NPE error will be thrown. If (names! = null).

Exception in thread "mainjava.lang.NullPointerException

    at com.cmower.dzone.stopdoing3things.NullDemo.main(NullDemo.java12) :

Copy the code

What if he doesn’t want the code to throw an NPE error without calling a null? Close your big eyes and think about it.

Well, the report, I’ve come up with, suggests that when xiao Er gets a name from the database, he returns a list of length 0 to indicate that the data is not found. A code example is as follows:

public class Null2Length0Demo {

    public static void main(String[] args) {

        List<String> names = getNamesFromDB();

        for (String name : names) {

            System.out.println(name);

        }

    }



    public static List<String> getNamesFromDB(a) {

        // The impersonator does not get the corresponding name from the database at this time.

        return Collections.emptyList();

    }

}

Copy the code

Note: collections.emptylist () is used to return an immutable emptyList, okay? If that doesn’t make sense, I’ll write another example that returns a mutable empty list, and you’ll see how it feels.

public class Null2Length0MutableDemo {

    public static void main(String[] args) {

        List<String> names = getNamesFromDB();

        for (String name : names) {

            System.out.println(name);

        }

    }



    public static List<String> getNamesFromDB(a) {

        // The impersonator does not get the corresponding name from the database at this time.

        return new ArrayList<>();

    }

}

Copy the code

New ArrayList<>() returns mutable, which means you can also change the list’s elements, such as adding, but deleting is impossible because there are no elements to delete.

You see, collections.emptyList () and new ArrayList<>() can both be used instead of NULL to reduce unnecessary nulls when printing lists and that pesky NPE.

Can you think of any other solutions besides my idea? Now, close your eyes again, and you might even think of one more: Java 8’s Optional class, a container class that can hold any type of element, and the isPresent() method returns true if the value exists. The Optional class neatly eliminates NPE by providing a number of specialized methods without explicitly null-checking.

Come on, read the example first for quick!

public class Null2OptionalDemo {

    public static void main(String[] args) {

        Optional<List<String>> list = getNamesFromDB();

        list.ifPresent(names -> {

            for (String name : names) {

                System.out.println(name);

            }

        });

    }



    public static Optional<List<String>> getNamesFromDB() {

        boolean hasName = true;

        if (hasName) {

            String [] names = {"Silent King II."."An interesting programmer."."Follow me in wechat search"};

            return Optional.of(Arrays.asList(names));

        }

        return Optional.empty();

    }

}

Copy the code

Don’t get it? Let me introduce you responsibly. Shake hands.

If the name exists in the database, wrap the return value with option.of () to return an object of type Optional. Why not use constructors, because constructors are private (source code shown below).

private Optional(T value) {

    this.value = value;

}

Copy the code

So why optional.of ()? Well, good question. Continue the source code.

public static <T> Optional<T> of(T value) {

    return new Optional<>(Objects.requireNonNull(value));

}

Copy the code

RequireNonNull (value) will throw an NPE if value is null. RequireNonNull (value) will throw an NPE if value is null.

2) If value is not null, create a normal Optional object using the new keyword.

What if there is no name in the database? Use option.empty () as the return value. Come on, continue the source code.

public static<T> Optional<T> empty(a) {

    @SuppressWarnings("unchecked")

    Optional<T> t = (Optional<T>) EMPTY;

    return t;

}

Copy the code

HMM, what is EMPTY?

private static finalOptional<? > EMPTY =new Optional<>(null);

Copy the code

Is a private constant (static + final) of the Optional class. Why, at this moment, I am reminded of Mr. Hans Christian Andersen’s fable — the Emperor’s new clothes, anyway, “the bottom is ugly.”

In this case, the ifPresent() method of the Optional object can be used to determine whether the value exists or not, and if only the value exists, the name can be printed directly as a Lambda expression.

list.ifPresent(names -> {

    for (String name : names) {

        System.out.println(name);

    }

});

Copy the code

It’s a little rough, isn’t it? But anyway, we can finally say goodbye to NULL NPE on the surface. Be a good person and be happy.

Well, my dear readers, that’s all for this article, and the best programmers you can see here. Original is not easy, do not want a free ticket, please praise for this article, this will be my writing more high-quality articles of the strongest power.

If you feel that the article is a little help to you, please wechat search “Silent King two” for the first time to read, reply [666] [1024] more I prepared for you 500G HD teaching video (has been classified), as well as dfactory technology niu people finishing the face by a copy, the source of this article has been included in the code cloud, portal ~