博客
关于我
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/

你可能感兴趣的文章
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
no session found for current thread
查看>>