I have an int array which has no elements and I'm trying to check whether it's empty.
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);
}
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;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Method to check array for null or empty also is present on org.apache.commons.lang:
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.isEmpty(array);
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) { }
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");
}
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.
The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.
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.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,
public static boolean isEmpty(#Nullable Object[] array) {
return (array == null || array.length == 0);
}
An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty.
Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.
int[] k = new int[3];
if(k.length == 0)
{
//do something
}
Related
I'm trying to remove an element from an array. I am running into an issue where when I run my program and remove a certain index. I get nulls in the place where the element/index should be removed entirely.
My output is when I execute list.display() in the main method is
Tom, Bob, Richard
However after I execute list.remove() and run the program. I get
null, null, Richard.
Any tips?
public class MyArrayList implements MyList {
private Object[] theList;
public MyArrayList()
{
theList = new Object[0];
}
public boolean add(Object toAdd){
if(toAdd != null) {
Object[] temp = new Object[theList.length + 1];
for(int i = 0; i < theList.length; i++) {
temp[i] = theList[i];
}
temp[theList.length] = toAdd;
theList = temp;
return true;
} else {
return false;
}
}
public Object remove(int index) {
if (index >= 0 && index < theList.length) {
Object[] temp = new Object[theList.length - 1];
theList[index] = null;
int j = 0;
for (int i = 0; i < theList.length; i++) {
if (i == index) {
continue;
}
temp[j++] = theList[i];
theList = temp;
}
return temp;
}
return null;
}
public class Main {
public static void main(String[] args) {
MyArrayList list = new MyArrayList();
list.add("Tom");
list.add("Bob");
list.add("Richard");
list.display();
list.remove(0);
list.remove(1);
list.display();
}
}
Where you call list.remove(0), you should be assigning the result back to list again. For example:
list = list.remove(0);
A couple of other things:
It's generally a bad idea to change the index variable within a loop. It's legal, but leads to logic errors that can be difficult to reason about and diagnose.
You're getting the null in your output because the remove method also mutates the theList when you execute:
theList[index] = null;
Since you're returning a copy of theList you don't need to also set that element of the theList array to null.
Since your code implements MyList which is not available in code, i could not run below sample on your code but you can have below logic in your code. You don't need extra temp array in remove method. Since it an array, you can start traversing array from index which has to be removed and start moving next element by one step before.
public Object remove(int index) {
if (theList == null || index < 0 || index >= theList.length) {
return theList;
}
for (int i = index; i < theList.length; i++) {
theList[i] = theList[i + 1];
}
return null;
}
You can trim array tail if it has more empty places based on some threshold.
the code is doing exactly what you asked it to do. Those removed values are null because you have this line
theList[index] = null;
Also think about what your intentions are.
list.remove(0); <- this will remove the first element so now list would be Rob, Richard
list.remove(1); <- this will remove the 2nd element of the modified list (Rob, Richard) so result would be Rob. This is probably not what you want.
instead of this
if (i == index) {
i++; // risk of out of bounds exception
}
you probably want this instead
if (i == index) {
continue;
}
I have an int array which has no elements and I'm trying to check whether it's empty.
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);
}
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;
}
}
ArrayUtils.isNotEmpty(testArrayName) from the package org.apache.commons.lang3 ensures Array is not null or empty
Method to check array for null or empty also is present on org.apache.commons.lang:
import org.apache.commons.lang.ArrayUtils;
ArrayUtils.isEmpty(array);
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) { }
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");
}
In Java 8+ you achieve this with the help of streams allMatch method.
For primitive:
int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)
For Object:
Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)
An int array is initialised with zero so it won't actually ever contain nulls. Only arrays of Object's will contain null initially.
The point here very simply is that the variable k isn't null because it points to the array. It doesn't matter that the array itself is empty. The null test in your post would only evaluate to true if the variable k didn't point to anything.
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.
Integer[] integers2 = new Integer[20];
integers2 = null; //array is nullified
// integers2[3] = null; //If I had int[] -- because it is priitive -- then I can't write this line.
if (integers2 == null) {
System.out.println("null Array");
}
if you are trying to check that in spring framework then isEmpty(Object[]) method in ObjectUtils class helps,
public static boolean isEmpty(#Nullable Object[] array) {
return (array == null || array.length == 0);
}
An int array without elements is not necessarily null. It will only be null if it hasn't been allocated yet. See this tutorial for more information about Java arrays.
You can test the array's length:
void foo(int[] data)
{
if(data.length == 0)
return;
}
public boolean empty() {
boolean isEmpty = true;
int i = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] != 0) {
i++;
}
}
if (i != 0) {
isEmpty = false;
}
return isEmpty;
}
This is as close as I got to checking if an int array is empty.
Although this will not work when the ints in the array are actually zero. It'll work for {1,2,3}, and it'll still return false if {2,0} but {0} will return true
I believe that what you want is
int[] k = new int[3];
if (k != null) { // Note, != and not == as above
System.out.println(k.length);
}
You newed it up so it was never going to be null.
You can also check whether there is any elements in the array by finding out its length, then put it into if-else statement to check whether it is null.
int[] k = new int[3];
if(k.length == 0)
{
//do something
}
im a newbie, i need to write a method that check if 2 arrays are equal in the values and order, if they are print true, else false
this is what i wrote and the result always true, if i try printing the values that the function recieve in the arrays for some reason they are all 0.
public static boolean areArraysEqual(int[] firstArr, int[] secArr) {
firstArr = new int[N];
secArr = new int[N];
System.out.println(firstArr.length);
if(firstArr.length != secArr.length){
return false;
}
if(firstArr == null || secArr == null){
return false;
}
for(int i = 0; i < firstArr.length; i++) {
if(firstArr[i] != secArr[i]) {
return false;
}
}
return true;
}
When you try to re-allocate the arguments firstArr and secArr, the original array contents get lost.
No need to re-allocte firstArr and secArr, since in java, array objects are passed by value, they can be used as-is for its contents.
The following code snippet is good enough:
public static boolean areArraysEqual(int[] firstArr, int[] secArr) {
if(firstArr == null || secArr == null || firstArr.length != secArr.length){
return false;
}
for(int i = 0; i < firstArr.length; i++) {
if(firstArr[i] != secArr[i]) {
return false;
}
}
return true;
}
You are creating two new arrays, which are initialized to all zeros with
firstArr = new int[N];
secArr = new int[N];
When you call areArraysEqual(int[] firstArr, int[] secArr) you are supplying two arrays already, there is no reason to create new ones.
Removing those two lines should get you going.
The issue with your code is that you are re-declaring the array. Remove firstArr = new int[N]; and secArr = new int[N]; from your code. Then it should work fine.
public static boolean areArraysEqual(int[] firstArr, int[] secArr) {
System.out.println(firstArr.length);
if(firstArr.length != secArr.length){
return false;
}
if(firstArr == null || secArr == null){
return false;
}
for(int i = 0; i < firstArr.length; i++) {
if(firstArr[i] != secArr[i]) {
return false;
}
}
return true;
}
Side note: If this is not for academic/competitive purpose use Array.equals(firstArr, secArr)
Nothing the already submitted answers don't cover, but you've got far too much code written for this. Try this:
public boolean compareArrays(int[] arr1, int[] arr2) {
if (Arrays.equals(arr1, arr2)) {
return true;
}
return false;
}
Arrays.equals covers order and size, no need to check for nulls either, that should be handled by the caller, after all, null does equal null and there for the arrays are equal.
What is the best way to check if array is null value or if the array contents are null in combination in 1 statement in Java 6:
if ((myArray[0] != null) || (myArray[1] != null) || (myArray!= null)) {
...
}
To have it check for any value, I'd use allMatch. It's also important to check for array != null first, otherwise you'll get an Exception if it is.
if (array == null || Arrays.stream(array).allMatch(Objects::isNull))
Note that this won't work with java prior to version 8, OP edited his requirements after I posted the answer
Firstly, check if the array is not null itself. If the array is null, it makes no reason to iterate its elements since Java will throw the NullPointerException upon access to it:
if (myArray != null) {
// ...
}
Then inside the body of the condition iterate through all its elements and check if one of them is null.
boolean hasNull = false;
for (int i=0; i<myArray.length; i++) {
if (myArray[i] == null) {
hasNull = true;
break; // to terminate the iteration since there is no need to iterate more
}
}
This one-line solution (thanks for the warning from #Napstablook). The condition is evaluated as true if the array itself is null or one of its element is null:
if !(myArray != null && myArray[0] != null && myArray[1] != null) { ... }
Be aware that the && operator works that if the left side is evaluated as false, it stops evaluating the rest of the condition because it will not affect the result. The same does || but with true. However, I suggest you avoid this solution since the index might overflow. Better use the for-loop mentioned above.
Check if Array is null:
String array[] = null;
if (array == null) {
System.out.println("array is null");
}
Check if array is Empty:
array = new int[0];
if (array.length == 0) {
System.out.println("array is empty");
}
Check for null at the same time:
int[] array = ...;
if (array.length == 0) { } // no elements in the array
if (array == null || iarray.length == 0) { }
Try this
if (myArray == null || Arrays.stream(myArray).allMatch(element-> element==null)) {}
Edit- For java 6, I really don't see this happening in one line. You can try this if one line is not necessary
boolean isNull = true;
if(myArray==null){
System.out.println("array is null");
}else{
for(Integer element: myArray){
if(element!=null){
System.out.println("array is not null");
isNull=false;
break;
}
}
if(isNull)
System.out.println("Array is null");
}
Instead Itreating Manullay the array, re use the existing collection for this case.
Convert Array Into List
Check Null is present in list or not using contains() method;
Please find the sample code:
public static void main(String[] args) {
Integer[] array = new Integer[3];
array[0] = 1;
array[1] = null;
array[2] = 2;
System.out.println(Arrays.asList(array).contains(null));
}
for example this
boolean isNullOrContainsNull = array == null || Arrays.asList(array).contains(null);
checks in a line whether the array is null or contains null elements
If you want to check whether the array is null or empty or all elements are null take
boolean containsNothingUseful = array == null
|| array.length == 0
|| !new HashSet<String>(Arrays.asList(array))
.retainAll(Arrays.asList((String)null));
(assuming a String[] array)
Uses the Collection#retainAll() method which returns true when there were other values present, i.e. the inverse of "containsOnly"
Using this one liner is actually fairly inefficient and one better uses a method like below which doesn't create lots of temporary objects and mutates collections etc.
public static boolean containsNothingUseful(String[] array) {
if (array == null || array.length == 0)
return true;
for (String element : array) {
if (element != null)
return false;
}
return true;
}
// ...
if (containsNothingUseful(myArray)) { .. }
public static boolean isComponentBefore(GuiInterface component) {
int index = 0;
for (int i = 0; i < components.size(); i++) {
if (components.get(i).getName() == component.getName()) {
if(components.get(i- 1) == null){
return false;
}
}
}
return true;
}
I currently use this, though this can lead to ConcurrentModificationExceptions & it isn't working because it keeps throwing ConcurrentModificationExceptions whenever I try to see if the element before the element passed in is null.
I was wondering if there are other ways to do this.
Looking at your logic, you will a NullPointerException incase the component in the ArrayList before the given component is null, because components.get(i) would be null and components.get(i).getName() will throw the NPE.
You can try to change the logic here a bit. For every null element in the list, check if the next component is the component you're searching for and return accordingly.
for (int i = 0; i < components.size(); i++) {
if (components.get(i) == null) { // If a particular element is null, check if the next element is what you want
if(components.get(i+1).getName().equals(component.getName())) { // you need to handle the edge case for i+1 as well for the last iteration
return false;
}
}
}
Note that you need to compare the Strings using equals() method and not the == operator. You also need to handle the corner case of i+1 for the last iteration.
This line
if (components.get(i).getName() == component.getName()) {
Should be
if (components.get(i).getName().equals(component.getName())) {
However, your condition can never happen. If component.get(i-1) is null, then in the previous loop iteration
components.get(i).getName() // <-- null pointer exception, so
component.get(i-1) must not be null and you need to hope that i isn't 0 or you'd get an index out of bounds exception.
Use an iterator
e.g
int i = 0;
Iterator<GuiInterface > it = components.iterator();
while (it.hasNext()) {
i++;
GuiInterface thisComp = it.next ();
if (thisComp.getName().equals(component.getName())) {
if(i > 0 && components.get(i- 1) == null){ // this code does not make sense
return false;
}
}
}
Assuming the passed component is not in your list:
public static boolean isComponentBefore(GUIComponent component) {
// Start at 1 to avoid IndexOutOfBounds
for(int i = 1; i < components.size(); i++) {
if (components.get(i).getName().equals(component.getName())) {
return components.get(i - 1) != null;
}
}
// Given component is not in the list, or the list only has one element
return false;
}
Assuming the passed component is in the list:
public static boolean isComponentBefore(GUIComponent component) {
int index = components.indexOf(component);
return index > 0 && components.get(index - 1) != null;
}