Java,巧妙的方法来替换“if not null”陈述?
我有一个充满 long
的 Vector
。
我希望能够始终在 Vector 上调用 getFirstElement()
,然后执行操作,例如 addToOtherVector()
。我希望能够不用担心原始向量是否确实有返回值。我想我可以通过重写 addToOtherVector()
来做到这一点,如下所示:
//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
}
但我不确定我需要做什么,因为它不接受 null
作为参数?
我这样做的原因是因为我不希望每次尝试检索时都检查向量的大小
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 addToOtherVector()
. 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需用基类重写该方法即可。由于
Number
是Long
、Integer
等的基类,只需使用该类:Just override the method with a base class. Since
Number
is the base class toLong
,Integer
, etc. just use that one :