How can I check whether an array is null / empty?

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

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

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); }

回答1:

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" 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"); }

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;   } }

or

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


回答2:

ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty



回答3:

Look at its length:

int[] i = ...; if (i.length == 0) { } // no elements in the array

Though it's safer to check for null at the same time:

if (i == null || i.length == 0) { }


回答4:

I am from .net background. However, java/c# are more/less same.

If you instantiate a non-primitive type (array in your case), it won't be null.
e.g. int[] numbers = new int[3];
In this case, the space is allocated & each of the element has a default value of 0.

It will be null, when you don't new it up.
e.g.

int[] numbers = null; // changed as per @Joachim's suggestion. if (numbers == null) {    System.out.println("yes, it is null. Please new it up"); }


回答5:

An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.



回答6:

I tested as below. Hope it helps.

Integer[] integers1 = new Integer[10];         System.out.println(integers1.length); //it has length 10 but it is empty. It is not null array         for (Integer integer : integers1) {             System.out.println(integer); //prints all 0s         }  //But if I manually add 0 to any index, now even though array has all 0s elements //still it is not empty //        integers1[2] = 0;         for (Integer integer : integers1) {             System.out.println(integer); //Still it prints all 0s but it is not empty             //but that manually added 0 is different         }  //Even we manually add 0, still we need to treat it as null. This is semantic logic.          
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!