I wanted to know if this code is valid for checking whether an array is empty, or should I check for null?
if(arrayName={})
System.out.println("array empty");
else System.out.println("array not empty");
Thank you!
One more way to detect duplication in the java array is adding every element of the array into HashSet which is a Set implementation. Since the add(Object obj) method of Set returns false if Set already contains an element to be added, it can be used to find out if the array contains duplicates in Java or not.
To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.
The array can be checked if it is empty by using the array. length property. This property returns the number of elements in the array.
To check if an array is empty or not, you can use the .length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.
In array class we have a static variable defined "length", which holds the number of elements in array object. You can use that to find the length as:
if(arrayName.length == 0)
System.out.println("array empty");
else
System.out.println("array not empty");
I would consider using ArrayUtils.is empty by adding Apache Commons Lang from here http://commons.apache.org/proper/commons-lang/download_lang.cgi
The big advantage is this will null check the array for you in a clean and easily readible way.
You can then do:
if (ArrayUtils.isEmpty(arrayName) {
System.out.printLn("Array empty");
} else {
System.out.printLn("Array not empty");
}
As poited out in the other answers, the length
property of Array
will give the length of the array. But it is always recommended to check if the array is null
before doing any operation on it or else it will throw NullPointerException
if the array is null
.
if (array != null) {
if (array.length == 0)
System.out.println("Empty Array Size=0");
else
System.out.println("Array Not Empty - Size = " + array.length);
} else
System.out.println("array is null");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With