如何检查数组是否为空/空? [英] How can I check whether an array is null / empty?

查看:63
本文介绍了如何检查数组是否为空/空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有元素的 int 数组,我正在尝试检查它是否为空.

I have an int array which has no elements and I'm trying to check whether it's empty.

例如,为什么下面代码中 if 语句的条件永远不为真?

For example, why is the condition of the if-statement in the code below never true?

int[] k = new int[3];

if (k == null) {
    System.out.println(k.length);
}

推荐答案

null 数组和空数组之间有一个主要区别.这是对 null 的测试.

There's a key difference between a null array and an empty array. This is a test for null.

int arr[] = null;
if (arr == null) {
  System.out.println("array is null");
}

这里的空"没有官方意义.我选择将空定义为具有 0 个元素:

"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:

arr = new int[0];
if (arr.length == 0) {
  System.out.println("array is empty");
}

空"的另一种定义是如果所有元素都是null:

An alternative definition of "empty" is if all the elements are null:

Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
  if (arr[i] != null) {
    empty = false;
    break;
  }
}

Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
  if (ob != null) {
    empty = false;
    break;
  }
}

这篇关于如何检查数组是否为空/空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆