Java 中原始数据类型和引用数据类型共存

Coexistance of primitve and reference data types in Java

我总是问自己这个问题:为什么 Java 设计者在他们的语言中引入了原始类型和引用类型。换句话说,为什么会存在两种可以实现相同目标的数据类型,例如 (int & java.lang.Integer), (float & java.lang.Float) ...谁能解释一下这个问题?

Java 有基元因为 :

  1. They are fast. (when compared to Objects)
  2. They have less overhead. (when compared to Objects)
  3. They actually make life easier for people with C/C++ background and gives them the same feel (almost).

Java 有包装器,因为 :

  1. In certain data structures like Collections, only objects are allowed to be added because when doing Garbage Collection, the GC treats all these things only as Objects and then performs operations on them.

  2. Using Wrappers (Objects) instead of primitives in Collections is more of a design choice because it allows general behavior of methods. For example equals() , contains() on collections work on the basis of method overriding which cannot be done on primitives.

基元比引用类型更快(在小循环中几乎察觉不到,但在大操作中,差异很明显),使具有 c/c++ 背景的人阅读代码更容易,并且通常是更好地优化了基本类型的通用操作。

但是请考虑 Java 的某些部分(集合、泛型、反射...)需要 类 而不是基本类型,因此为此添加了包装器(加上装箱和拆箱) .此外,包装器可以为空,而基本类型则不能,这在某些操作中也可能需要。