0

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??

randomizertech
  • 2,309
  • 15
  • 48
  • 85

3 Answers3

3

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

d-live
  • 7,926
  • 3
  • 22
  • 16
2

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;
    }
 }
Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
  • Thank you very much. I fixed it, I did have some null values indeed. I just changed the items.length to the counter which keeps the next empty value in the array. – randomizertech May 25 '11 at 02:31
1

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;
}
OscarRyz
  • 196,001
  • 113
  • 385
  • 569