Java 中的原始类型与对象类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18333648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:37:22  来源:igfitidea点击:

Primitive vs Object type in Java

javaobjectprimitive

提问by Ruchira Gayan Ranaweera

This question came to my mind because I have read somewhere that Java is not a pure Object oriented language since it is using primitives (which are not objects). I can agree with that. Now my problem is why we are using primitives/wrapperswhile we already have Object in same type?

我想到了这个问题,因为我在某处读到 Java 不是纯面向对象的语言,因为它使用原语(不是对象)。我可以同意。现在我的问题是为什么我们primitives/wrappers在已经有相同类型的 Object 的情况下使用?

As an example if we consider Integer, It has same value limit as intother than object behavior. why still Java use primitivesunder these condition?

例如,如果我们考虑Integer,它与int对象行为以外的值限制相同。为什么primitives在这些条件下仍然使用Java ?

As my opinion, if Java only use Object type Autoboxing and Unboxingno need. Also there is no primitive for String by the way.

在我看来,如果 Java 只使用对象类型自动装箱和取消装箱就没有必要了。顺便说一下,也没有 String 的原语。

回答by blackpanther

One reason is due to memory usage. Primitives, such as int, floatetc. require less memory allocations (I think 4 bytes) in comparison to Objects which are at the very least 8 bytes. Please see the following reference:

原因之一是由于内存使用。原语,诸如intfloat等需要较少的存储器分配(我认为4个字节)相比,它们是至少是8个字节的对象。请参阅以下参考资料

In addition, a lot of arithmetic (numeric) is completed with the use of primitives rather than their Object equivalents and this is another reason why they are quite critical in the Java language.

此外,许多算术(数字)是通过使用原语而不是它们的 Object 等价物来完成的,这也是它们在 Java 语言中非常重要的另一个原因。