سؤال

I have this method in my code

public boolean has(AnyType x){

        for(int i=0; i<items.length; i++)
            if(items[i] == x)
                return true;

        return false;
    }

and I want to rewrite the if statement to use the compareTo() method, and according to what I remember it should be something like this:

if(items[i].compareTo(x) == 0)

But that is giving me an error

Exception in thread "main" java.lang.NullPointerException

Any ideas of what I might be doing wrong??

هل كانت مفيدة؟

المحلول

NullPointer Exception is thrown when an application attempts to use null in a case where an object is required. Check with your items[i] values. One of the value must be a null, so that's why the compiler is throwing a NullPointerException.

if(items[i].compareTo(x) == 0)

When you do this, you are trying to compare a null value with x, which indeed throws a NullPointerException.

Do check for the not-a-null-value test. Try this,

public boolean has(AnyType x){

      for(int i=0; i<items.length; i++) {
            if(items[i] != null && items[i] ==x)
                   return true;
         return false;
    }
 }

نصائح أخرى

One of your items[] is null. Check if the elements are properly set to non-null values.

One of your items is null, you can validate it before attempting to call compareTo.

You can also use the enhanced for loop:

public boolean has(AnyType x){
    for( AnyType n : items ) {
        if( ( n == null && n == x )  || 
            ( n != null && n.compareTo( x ) == 0  ) ) { 
            return true;
        }
     }
     return false;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top