java-collection中的null,isEmpty

时间:2025-04-13 18:47:35

只使用java utils包的isEmpty.

第一种情况:实例化list,但是size为空。

 

	List<String> list =new ArrayList<>();
		if (()) {
			("1");
		}
		if (!()) {
			("2");
		}
		if (list != null) {
			("3");
		}
                if (list != null && () > 0) {
                        ("4");
                }


输出:

 

 

1
3


第二种情况:add值到list中

 

 

 

 

		List<String> list =new ArrayList<>();
		("da");
		if (()) {
			("1");
		}
		if (!()) {
			("2");
		}
		if (list == null) {
			("3");
		}
                if (list != null && () > 0) {
                        ("4");
                }

输出:

 

 

2
4

第三种情况:只创建list的引用,不实例化。

 

 

List<String> list = null;
		if (()) {
			("1");
		}
		if (!()) {
			("2");
		}
		if (list != null) {
			("3");
		}
		if (list != null && () > 0) {
			("4");
		}

输出:

 

 

Exception in thread "main" 

 

改进办法:

使用;

(Collecions<extend>);

可以避免

异常