Reputation: 2329
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??
Upvotes: 0
Views: 725
Reputation: 46405
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;
}
}
Upvotes: 2
Reputation: 199234
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;
}
Upvotes: 1
Reputation: 8036
One of your items[] is null. Check if the elements are properly set to non-null values.
Upvotes: 3