int[] 和 Integer[] 数组 - 有什么区别? [英] int[] and Integer[] arrays - What is the difference?

查看:44
本文介绍了int[] 和 Integer[] 数组 - 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下基础知识:

  1. 任何Object都只存在于堆中,
  2. Array IS-A Object
  3. Integer IS-A Object
  1. Any Object lives only on heap,
  2. Array IS-A Object and
  3. Integer IS-A Object

我发现自己很难回答这样一个简单的问题:int[]Integer[] 之间有什么区别 JVM 内部?还是只在编译时"才有意义?

I find myself difficult to answer such a simple question: Is there any difference between int[] and Integer[] inside of JVM? Or it makes sense only at "compile-time"?

推荐答案

运行时存在差异.

int[] 是原始 int 值的数组.Integer[] 是一个对象"数组,保存对 Integer 对象的引用.

int[] is an array of primitive int values. Integer[] is an "object" array, holding references to Integer objects.

最重要的实际区别:int[] 不能保存 null 值.

Most important practical difference: int[] cannot hold null values.

但我仍然很困惑:int[] 是否只存储原始值?如果是这样 - 这是否意味着原始类型可以在没有被包装的情况下存在于堆上?

But I'm still confused: does int[] store just a primitive values? If so - doesn't it mean that primitive types can live on heap without being wrapped?

int[] 确实存储原始类型.而数组本身存在于堆中.但是,这些原语是作为数组的一部分分配的.它们不会单独存储在堆的其他地方.这与原始字段如何成为对象实例的一部分非常相似:对象在堆上,其字段是该对象的组成部分(而对于非原始字段,仅引用存储在对象内部而引用指向的目标实例单独存放在堆上)

int[] does store primitive types. And the array itself lives on the heap. However, those primitives are allocated as part of the array. They are not stored separately elsewhere on the heap. This is very similar to how a primitive field is part of an object instance: The object is on the heap, and its field is an integral part of that object (whereas for a non-primitive field, only the reference is stored inside the object and the target instance that reference points at is stored separately on the heap).

你可以说 int 被包裹"在数组中.

You could say the int is "wrapped" inside the array.

这篇关于int[] 和 Integer[] 数组 - 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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