Java中的原始vs对象类型 [英] Primitive vs Object type in Java

查看:95
本文介绍了Java中的原始vs对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题出现在我的脑海中,因为我在某处读过Java不是纯粹的面向对象语言,因为它使用的是原语(不是对象)。我可以同意。现在我的问题是为什么我们使用 primitives / wrappers ,而我们已经有相同类型的Object?

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/wrappers while we already have Object in same type?

作为一个例如,如果我们考虑 Integer ,它与 int 具有相同的值限制,而不是对象行为。为什么Java仍然在这些条件下使用 primitives

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

正如我所说,如果Java只使用Object类型 Autoboxing和Unboxing 不需要。顺便说一下,String也没有原语。

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

推荐答案

一个原因是内存使用情况。与对象相比,基元,例如 int float 等需要更少的内存分配(我认为是4个字节)最少8个字节。请参阅以下参考

One reason is due to memory usage. Primitives, such as int, float etc. 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:

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

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.

这篇关于Java中的原始vs对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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