博客
关于我
Java中判断数组是否为空?
阅读量:755 次
发布时间:2019-03-23

本文共 1402 字,大约阅读时间需要 4 分钟。

###判断数组是否为空?

技术人员在判断一个数组是否为空时,通常会首先检查该数组是否为null,然后再判断其元素数量是否为0。例如:

String[] suzu = new String[] {};
if (suzu == null) {
// 没有元素,数组为null
} else if (suzu.length == 0) {
// 数组不为null,但没有元素
}

此外,使用java.util.Arrays类中的isNotEmpty方法可以简化代码:

if (!Arrays.isArray(suzu)) {
throw new IllegalArgumentException("suzu is not an array");
}
if (!Arrays.isNotEmpty(szu)) {
// 代码执行到这里说明suzu不为空且不为null
}

###判断集合是否为空?

当需要判断集合是否为空时,可以通过同时检查集合是否为null和其大小是否为0来实现。例如,使用org.apache.commons.collections.CollectionUtils中的isEmpty方法:

List
list = Lists.newArrayList();
if (CollectionUtils.isEmpty(list)) {
// 集合为空
} else {
// 集合不为空
}

若集合不为null且不为空,可以使用CollectionUtils.isNotEmpty方法:

if (CollectionUtils.isNotEmpty(list)) {
// 集合不为空且不为null
}

###判断字符串是否为空?

判断一个字符串是否为空时,通常需要同时检查字符串是否为null、是否为空字符串或是否为空白字符。例如,使用org.apache.commons.lang3.StringUtils类:

String string = null;
if (StringUtils.isNotBlank(string)) {
// 字符串不为空且不为空白
} else {
// 字符串为空或为空白
}

如果想检查字符串是否为null且为空白,可以使用以下代码:

if (StringUtils.isBlank(string)) {
// 字符串为null、为空或为空白
}

###判断两个字符串是否相等?

判断两个字符串是否相等时,建议使用org.apache.commons.lang.ObjectUtils中的equals方法。这种方法可以避免空指针异常,并且正确处理字符串相等的逻辑:

String string1 = null;
String string2 = null;
if (ObjectUtils.equals(string1, string2)) {
// 两个字符串相等
} else {
// 两个字符串不相等
}

这种方法在如下情况下非常有用:

  • string1为null且string2也为null:返回true
  • string1为null或string2为null:返回false
  • 两个字符串内容相等:返回true
  • 其余情况:返回false

转载地址:http://raszk.baihongyu.com/

你可能感兴趣的文章
mysql - 视图
查看>>
MySQL - 解读MySQL事务与锁机制
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>