• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to exclude empty values from a Vector  RSS feed

 
Sharon Cowling
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to loop through my Vector and exclude any empty or null values.
The Vector will contain 12 or more values, of which 1 or more may contain the value, but there is a chance that quite a few will be empty, the code below just gives me a null pointer exception.
Can anybody tell me the right way to do this?
for (int i=0;i<locVector.size();i++){
if (locVector.elementAt(i).equals("")|| locVector.elementAt(i) == null){
locVector.removeElementAt(i);
}
}
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since nobody has said it yet, Welcome to JavaRanch!
It looks like you're having a little bit of confusion concerning what can be done with a null value. As your code demonstrates (by its failure), you can't test an object for equality using the equals(Object) method if the object is null - note the argument to the method can be null, not the object invoking the method.
For your purposes, a quick and easy solution would be to reverse the order of your tests in your if statement. That way, if the component has a null value, then the second test for equality wouldn't be performed on a null value (as the test would short circuit).
Here's some quick example code to consider:

Making sense?
Good Luck.
 
Sharon Cowling
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that, silly mistake on my behalf. Now thats sorted I'm still getting the wrong results out of the Vector, entering 2 out of the possible 12 entries, and I'm getting back my 2 values, and 5 empty strings, well they look like empty strings in the database, but I'm testing for that...any other way to test for a Vector element that does not contain a String value?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I'm understanding you correctly, the instanceof operator may be what you'd want to use. So, after your initial removal of null values:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!