Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use emptyList and EMPTY_LIST of Java Collections

Shulou Source: shulou.com Published: 2022-06-02 14:45:11 09月16日 Update

This article mainly introduces how to use emptyList and EMPTY_LIST of Java Collections. It is very detailed and has certain reference value. Friends who are interested must finish reading it.

The use of emptyList and EMPTY_LIST of Collections

When looking at the code written by the boss, when the result set is empty, he returns not null, but:

Return Collections.EMPTY_LIST

We all know that returning null is likely to cause a null pointer exception, which can be avoided by using emptyList or EMPTY_LIST unless you want to capture the null information

When we use the emptyList null method to return an empty collection, note that the empty collection is immutable.

Empty collections cannot use the add method. A UnsupportedOperationException exception will be reported. See the following source code:

Public void add (int index, E element) {throw new UnsupportedOperationException ();}

Empty collection objects cannot use the put method. An IndexOutOfBoundsException exception will be reported. See the following source code:

Public E get (int index) {throw new IndexOutOfBoundsException ("Index:" + index);}

However, no exception occurs for the for loop, as shown in the following example:

List list1 = Collections.emptyList (); for (String s:list1) {} for (int iTuno)

Tags: Method time source code face-to-face loop element content branch place example boy partner article if logic static will report obvious clear more or less the same Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Tech Info OPPO Reno Shulou Technology Xiaomi