null、javaコレクションのisEmpty

javautilsパッケージのisEmptyのみを使用してください。

最初のケース:リストをインスタンス化しますが、サイズは空です。

 

	List<String> list =new ArrayList<>();
		if (list.isEmpty()) {
			System.out.println("1");
		}
		if (!list.isEmpty()) {
			System.out.println("2");
		}
		if (list != null) {
			System.out.println("3");
		}
                if (list != null && list.size() > 0) {
                        System.out.println("4");
                }


出力:

 

 

1
3


2番目のケース:リストに値を追加する

 

 

 

 

		List<String> list =new ArrayList<>();
		list.add("da");
		if (list.isEmpty()) {
			System.out.println("1");
		}
		if (!list.isEmpty()) {
			System.out.println("2");
		}
		if (list == null) {
			System.out.println("3");
		}
                if (list != null && list.size() > 0) {
                        System.out.println("4");
                }

出力:

 

 

2
4

3番目のケース:インスタンス化せずにリストへの参照のみを作成します。

 

 

List<String> list = null;
		if (list.isEmpty()) {
			System.out.println("1");
		}
		if (!list.isEmpty()) {
			System.out.println("2");
		}
		if (list != null) {
			System.out.println("3");
		}
		if (list != null && list.size() > 0) {
			System.out.println("4");
		}

出力:

 

 

Exception in thread "main" java.lang.NullPointerException

 

改善方法:

使用org.apache.commons.collections.CollectionUtils;

CollectionUtils.isEmpty(Collecions <extend>);

回避できる

java.lang.NullPointerException异常

 

おすすめ

転載: blog.csdn.net/u010857795/article/details/50731311