-3

I followed the points made in this thread, but I get the error "the operator is undefinded for the argument types[...]"

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

My code:

public class Test{

private int[] array = new int [5];

  public int method(int i) {
      for(int s = 0; s <= array.length; s++) {
          if( array[s] != null) { //I get the error in here even though the highest upvoted answer in the linked question recommends this solution. I obviously cant check it for 0, because the user input can be 0.
            array[s] = i;
          } else {
             method(i);
        }
      }
   }
}

Thanks!

Mark
  • 3
  • 1
  • 2
    `s <= array.length` is *always* wrong as you will try to access past the bounds of the array (causing an exception) – UnholySheep Jul 15 '18 at 10:26
  • 1
    Also an `int[]` cannot have "empty" values in it - the default is 0, there is no way to set it to `null`. Either your array can be `null` or have a `length` of 0, there is nothing else you can do – UnholySheep Jul 15 '18 at 10:27
  • Ur right, didnt think of that but even by fixing it with array.length -1 my other issue still remains. – Mark Jul 15 '18 at 10:28

2 Answers2

2

You are getting this error as int is a primitive type. In your case array[s] returns an int not an Integer. Int can't be a null.

Change your array from int[] to Integer[] if you want to check null.

private Integer[] array = new Integer[5];
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
1

You have array of int which is primitive type, primitive types in Java can't be null so compiler gives error when checking if it is null, if you really want it you can use Integer which is wrapper class for int.

FilipRistic
  • 2,661
  • 4
  • 22
  • 31