Java, clever way to replace "if not null" statement?
I have a Vector
full of long
s.
I would like to be able to always call getFirstElement()
on a Vector and then perform an action, let's say addToOther开发者_如何学编程Vector()
. I want to be able to not worry whether or not there is actually a value to return from my original vector. I think I could do it by overriding addToOtherVector()
like so:
//Code to be called when my first vector is not empty
public void addToOtherVector(long s){
othervector.add(s);
}
//Code to be called when my first vector IS empty
public void addToOtherVector(something???){
//does nothing
}
but I'm not sure what i need to do for the something, as it won't accept null
as a parameter?
The reason I am doing this is because I don't wish to have to check the size of the vector each time I try to retrieve
Just override the method with a base class. Since Number
is the base class to Long
, Integer
, etc. just use that one :
//Code to be called when my first vector is not empty
public void addToOtherVector(long s){
othervector.add(s);
}
//Code to be called when my first vector IS empty
public void addToOtherVector(Number s){
if (s == null) {
return;
}
othervector.add(((Number) s).longValue());
}
import java.util.Vector;
public class Main {
static Vector otherVector = new Vector();
public static void main(String[] args) {
Vector originalVector = new Vector();
originalVector.add(1);
originalVector.add(null);
originalVector.add(2);
for (Object obj : originalVector) {
addToOtherVector(obj);
}
}
public static void addToOtherVector(long s) {
otherVector.add(s);
System.out.println("adding " + s + " to vector");
}
public static void addToOtherVector(Object obj) {
System.out.println("not adding " + obj + " to vector");
}
}
精彩评论