Reputation: 45
In the following code, i have a method to get a Vector
of persons with the same zodiac sign. persoane
is a Vector<Persoana>
. I keep getting a NullPointerException
at the if condition (persoane
is definetly not null). I am unable to see why. Any help would be greatly appreciated
public Vector<Persoana> cautaDupaZodie(String zodie)
{
Vector<Persoana> rezultat= new Vector<Persoana>();
for(int i=0; i<persoane.size(); i++)
{
if(persoane.get(i).getData().getZodie().equals(zodie)) //the exception occurs here
{
rezultat.add(persoane.get(i));
}
}
return rezultat;
}
Upvotes: 3
Views: 236
Reputation: 384006
First of all, you should use List<Person>
if possible. Then, I recommend breaking the method chain to a smaller steps to see which exact step is failing.
public List<Person> searchZodiac(String zodiac) {
assert zodiac != null; // if it fails here, zodiac == null
List<Person> result = new ArrayList<Person>();
for (Person p : persons) {
Data d = p.getData(); // if it fails here, p == null
String z = d.getZodiac(); // if it fails here, d == null
if (z.equals(zodiac)) { // if it fails here, z == null
result.add(p);
}
}
return result;
}
Upvotes: 1
Reputation: 27239
if(persoane.get(i).getData().getZodie().equals(zodie))
break the above line into several parts.Here getData must be returning null so you are getting NullPointerException
Upvotes: 1
Reputation: 346526
It could be any of the following:
persoane
contains a null
at any indexpersoane
returns null
for getData()
getData()
results retruns null
for getZodie()
To investigate further, you'd best break up that chain of methods and add a conditional breakpoint. Additionally, rethink your design - this kind of "method operating on deeply nested, behaviourless data structure" is bad for this and other reasons.
Upvotes: 1
Reputation: 24630
You may add some "tracing" code:
public Vector<Persoana> cautaDupaZodie(String zodie)
{
Vector<Persoana> rezultat= new Vector<Persoana>();
for(int i=0; i<persoane.size(); i++)
{
System.err.println(persoane.get(i));
System.err.println(persoane.get(i).getData());
System.err.println(persoane.get(i).getData().getZodie());
if(persoane.get(i).getData().getZodie().equals(zodie)) //the exception occurs here
{
rezultat.add(persoane.get(i));
}
}
return rezultat;
}
Upvotes: 1
Reputation: 262834
persoane.get(i).getData().getZodie()
break that down into several lines to see where the NPE occurs.
Also, consider using the for-each loop.
for (Persoana persoana: rezultat){
...
}
Upvotes: 2
Reputation: 55594
NullPointerException
occurs, when you try to call a method on an Object
that is null
.
This means that one of the following returns null
:
get(i)
getData()
getZodie()
Add them one by one to find out what actually is causing your exception.
Upvotes: 5