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

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

问题描述

我有 int 数组,它没有元素,我试图检查它是否为空。

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

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

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

int[] k = new int[3];

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


推荐答案

a之间存在重大差异 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");
}

空这里没有官方含义。我选择将empty定义为具有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");
}

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天全站免登陆