Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

java - 如何检查数组是否为空/空?(How can I check whether an array is null / empty?)

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

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

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

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

int[] k = new int[3];

if (k == null) {
    System.out.println(k.length);
}
  ask by Ankit Sachan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's a key difference between a null array and an empty array.

(null数组和空数组之间有一个关键区别。)

This is a test for null .

(这是对null的测试。)

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

"Empty" here has no official meaning.

(这里的“空”没有官方含义。)

I'm choosing to define empty as having 0 elements:

(我选择将空定义为具有0个元素:)

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

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

(如果所有元素均为null则可以定义为“空”:)

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

or

(要么)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...