How to check for a null position in the vector

2

Why does if(array[i] == null) not correct?

What would be the best way to check if that vector space is "empty"?

    
asked by anonymous 23.06.2016 / 20:39

2 answers

3

There is a fundamental 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");
}

For you to check array is empty use;

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

An alternative definition of "empty" is, if all 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;
  }
}  

Elements in primitive arrays can not be empty. They are always initialized to something (usually 0 for int arrays, but it depends on how you declare the array).

If you declare the array like this, for example:

Reference Here .

int [] myArray ;
myArray = new int[7] ;

All elements will default to 0. An alternative syntax for declaring arrays is

int[] myArray = { 12, 7, 32, 15, 113, 0, 7 };

Where the initial values for an array (of size seven in this case) are given in the braces {}.

Reference Here .

    
23.06.2016 / 20:57
2

Considering what you said in this comment :

  

the vector is of type int - Dr.G

The problem is as follows:

The array type is int[] . This means that array[i] is of type int . The problem is to compare int with null . Primitive types will never be null and the compiler knows this. So it will give you a compilation error:

incomparable types: int and <null>
    
23.06.2016 / 21:02