目录
基本数据类型
对象类型
集合类型
综合示例
总结
工具类 hutool
基本数据类型
基本数据类型在Java中不能为null
,它们有默认值。基本数据类型包括:
int
float
double
char
boolean
byte
short
long
因此,对基本数据类型不需要进行判空检查,只需要处理它们的默认值。
基本数据类型默认值:
整型(Integer Types):
byte
:默认值为0
short
:默认值为0
int
:默认值为0
long
:默认值为0L
浮点型(Floating-Point Types):
float
:默认值为0.0f
double
:默认值为0.0d
字符型(Character Type):
char
:默认值为'\u0000'
(null字符)布尔型(Boolean Type):
boolean
:默认值为false
对象类型
对于对象类型(如String),判空通常是检查它们是否为null
。
String str = null;
if (str == null) {System.out.println("String is null");
} else {System.out.println("String is not null");
}
集合类型
Java中的集合类型包括List
、Set
、Map
等。通常需要检查集合对象是否为null
,然后再检查集合是否为空(即没有元素)。
List
List<String> list = null;// 判空检查
if (list == null) {System.out.println("List is null");
} else if (list.isEmpty()) {System.out.println("List is empty");
} else {System.out.println("List is not empty");
}
Set
Set<String> set = null;// 判空检查
if (set == null) {System.out.println("Set is null");
} else if (set.isEmpty()) {System.out.println("Set is empty");
} else {System.out.println("Set is not empty");
}
map
Map<String, String> map = null;// 判空检查
if (map == null) {System.out.println("Map is null");
} else if (map.isEmpty()) {System.out.println("Map is empty");
} else {System.out.println("Map is not empty");
}
综合示例
import java.util.*;public class NullCheckExample {public static void main(String[] args) {String str = null;List<String> list = new ArrayList<>();Set<String> set = null;Map<String, String> map = new HashMap<>();checkNull(str);checkNull(list);checkNull(set);checkNull(map);}public static void checkNull(String str) {if (str == null) {System.out.println("String is null");} else {System.out.println("String is not null");}}public static void checkNull(List<?> list) {if (list == null) {System.out.println("List is null");} else if (list.isEmpty()) {System.out.println("List is empty");} else {System.out.println("List is not empty");}}public static void checkNull(Set<?> set) {if (set == null) {System.out.println("Set is null");} else if (set.isEmpty()) {System.out.println("Set is empty");} else {System.out.println("Set is not empty");}}public static void checkNull(Map<?, ?> map) {if (map == null) {System.out.println("Map is null");} else if (map.isEmpty()) {System.out.println("Map is empty");} else {System.out.println("Map is not empty");}}
}
总结
- 基本数据类型:不需要判空,只需处理默认值。
- 对象类型:检查是否为
null
。 - 集合类型:先检查是否为
null
,再检查是否为空(isEmpty()
)。
工具类 hutool
String
String str = " ";
boolean empty = StrUtil.isEmpty(str);
boolean blank = StrUtil.isBlank(str);
//false
System.out.println(empty);
//true
System.out.println(blank);
集合
//判断列表是否为空 list!=null && list.size()!=0
ArrayList<Object> newList = CollUtil.newArrayList();
System.out.println(CollUtil.isEmpty(newList));
map
//将多个键值对加入到Map中Map<Object, Object> map = MapUtil.of(new String[][]{{"key1", "value1"},{"key2", "value2"},{"key3", "value3"}});
//判断Map是否为空
System.out.println(MapUtil.isEmpty(map));