Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use emptyList and EMPTY_LIST of Java Collections

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report