How to check null element if it is integer array i

2020-08-09 10:39发布

问题:

I'm quite new to Java and having an issue checking null element in integer array. I'm using Eclipse for editor and the line that checks null element is showing error:

Line that complains:

if(a[i] != null) {

Error msg from Eclipse:

The operator != is undefined for the argument type(s) int, null

In PHP, this works without any problem but in Java it seems like I have to change the array type from integer to Object to make the line not complain (like below)

Object[] a = new Object[3];

So my question is if I still want to declare as integer array and still want to check null, what is the syntax for it?

Code:

public void test() {
        int[] a = new int[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //this line complains...
                System.out.println('null!');
            }
        }
    }

回答1:

In Java, an int is a primitive type and cannot be null. Objects, however, are stored as references, so if you declare an object reference but do not make a new object, the reference will be null.

Integers are object wrappers around ints, meaning they can be null.

public void test() {
        Integer[] a = new Integer[3];
        for(int i=0; i<a.length; i++) {
            if(a[i] != null) { //should now compile
                System.out.println('null!');
            }
        }
    }


回答2:

On primitive vs reference types

An int is a primitive type, which is distinct from a reference type. Only reference types can have the value null.

References

  • JLS 4.2 Primitive Types and Values
  • JLS 4.3 Reference Types and Values

Related questions

  • Is Java fully object-oriented?
  • Is java 100% object oriented ?

On Integer vs int

java.lang.Integer is in fact a reference type, the designated "box" type for the primitive type int. Thus, an Integer variable can have the value null.

With the introduction of autoboxing in Java, conversions from int to Integer and vice versa can be done implicitly. But do keep in mind that they are very different types, and in fact an attempt to unbox null will throw NullPointerException.

References

  • Java Language Guide/Autoboxing
  • JLS 5.1.7 Boxing Conversion

Related questions

  • What is the difference between an int and an Integer in Java/C#?
  • Why does autoboxing in Java allow me to have 3 possible values for a boolean?

On consequences of Integer being a reference type

One consequence is already mentioned: an Integer variable can have a null value. Another one is that the == operator on two Integer is a reference identity comparison, not numerical equality.

System.out.println(new Integer(0) == new Integer(0)); // prints "false"

Whenever possible, you should prefer primitive types to boxed types. Here's a quote from Effective Java 2nd Edition, Item 49: Prefer primitive types to boxed primitives (emphasis by author):

In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

Related questions

  • Is it guaranteed that new Integer(i) == i in Java?
    • Goes in detail about how == behaves for Integer and int operands

When Integer must be used

There is one glaring exception where Integer must be used over int: generics. Type parameters in Java generics must be reference types. So you can NOT have a List<int> in Java; you must use a List<Integer> instead.

Related questions

  • Java noob: generics over objects only?

See also

  • Java Tutorials/Generics

On using the appropriate data structure

If you must have an int[] that permits null values, then the quick answer is to use Integer[]. Since you now have an array of reference types, some elements can be null. Be aware of all the consequences of working with reference types, or you may come across surprises.

At this point, however, I'd seriously consider using a List<Integer> instead (see Effective Java 2nd Edition: Prefer lists to arrays). Lists are much more feature-rich than arrays, and it interoperates well with the larger Java Collections Framework.

API references

  • java.util.List
  • Java Collections Framework Guide


回答3:

An 'int' cannot be null. An Integer (which is an object) can. So, as @Justin said, Integer[] will allow you to test for null, but if int[] is working for you, then you don't need to bother testing for null because it can't happen.



回答4:

int is a primitive type in java, and cannot be null. Only objects can be null.



回答5:

You can use arr[i] != '\0' like this. It worked for me.

public class IntNullCheck {
public static void main(String[] args) {

    int[] intarr = new int[5];
    intarr[0] = 7;
    intarr[3] = 9;

    for(int n : intarr){
        if(n != '\0'){
            System.out.println(n);
        }else
            System.out.println("Null");
    }
}
}