int不会覆盖Java中的Integer [英] int does not override Integer in Java

查看:82
本文介绍了int不会覆盖Java中的Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用方法签名函数

I had a function in Java with method signature

public void myMethod (int someInt, String someString) 

在我的抽象类中我用方法覆盖了它

in my abstract class and I had over-ridden it with method

public void myMethod (Integer someInt, String someString)

过度骑行不起作用。这是不一致的吗?我认为自动装箱也适用于方法签名覆盖。

The over ride does not work. Is this an inconsistency ? I thought auto-boxing applied to method signature over-ride as well.

推荐答案

int Integer 是两种不同的类型。为了方便程序员,Autoboxing在源代码级别上模糊了这种区别,但并没有改变它们实际上是两个非常不同类型的事实。

int and Integer are two different types. Autoboxing blurs the distinction at the source code level for the convenience of programmers, but does not change the fact that they are in fact two very different types.

因此,你不能 @Override 一个带 int 的方法,其中一个方法需要整数,反之亦然。

As such, you can not @Override a method that takes an int with one that takes an Integer and vice versa.

请注意,在声明采用整数而不是 int 。以下摘录自 Effective Java 2nd Edition,Item 49:Prefer primitives to boxed primitives

Note that you should probably think twice before declaring a method to take an Integer instead of an int. Here's an excerpt from Effective Java 2nd Edition, Item 49: Prefer primitives to boxed primitives:


总之,只要有选择,就可以使用原始优先于盒装原语。原始类型更简单,更快捷。如果你必须使用盒装基元,小心!自动装箱减少了使用盒装基元的冗长度,但没有降低危险性。当您的程序将两个盒装基元与 == 运算符进行比较时,它会进行身份比较,这几乎肯定不是您想要的。当你的程序执行涉及盒装和未装箱原语的混合类型计算时,它会进行拆箱,当你的程序进行拆箱时,它会抛出 NullPointerException 。最后,当你的程序框原始值时,它可能导致昂贵和不必要的对象创建。

In summary, use primitives in preference to boxed primitive whenever you have the choice. Primitive types are simpler and faster. If you must use boxed primitives, be careful! Autoboxing reduces the verbosity, but not the danger, of using boxed primitives. When your program compares two boxed primitives with the == operator, it does an identity comparison, which is almost certainly not what you want. When your program does mixed-type computations involving boxed and unboxed primitives, it does unboxing, and when your program does unboxing, it can throw NullPointerException. Finally, when your program boxes primitive values, it can result in costly and unnecessary object creations.

有些地方你别无选择但要使用盒装基元,例如泛型,但你应该认真考虑是否有合理使用盒装基元的决定。

There are places where you have no choice but to use boxed primitives, e.g. generics, but otherwise you should seriously consider if a decision to use boxed primitives is justified.

  • Java Language Guide/Autoboxing
  • What is the difference between an int and an Integer in Java/C#?
  • Is it guaranteed that new Integer(i) == i in Java? (YES!!! The box is unboxed, not other way around!)
  • Why does int num = Integer.getInteger("123") throw NullPointerException? (!!!)
  • Why null == 0 throws NullPointerException in Java?

这篇关于int不会覆盖Java中的Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆