Java 中的数组及其在内存中的存储方式 [英] Arrays in Java and how they are stored in memory

查看:30
本文介绍了Java 中的数组及其在内存中的存储方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 Java 中的数组设置.为什么必须在创建数组后为数组中的每个对象初始化空间.它是如何像这样存储在内存中的:

I'm trying to understand the array setup in java. Why must you initialize space for each each object in the array, after you have created the array. How is it stored in memory like this:

[object][object]

或者像这样:

[*class]->[object]  
[*class]->[object]

换句话说,就是在内存中实际执行的操作.array[0] = new class() 是否只是返回对内存中保留位置的引用,并且 class[] array = new class[10] 语句创建了一些东西沿着 10 个指针的行,这些指针后来由新语句分配?

In other words, what is actually being done in memory. Does array[0] = new class() just return a reference to a reserved location in memory, and the class[] array = new class[10] statement create something along the lines of 10 pointers, which are later assigned to by the new statements?

推荐答案

Java 中的数组存储两种事物之一:原始值 (int, char, ...) 或引用(又名指针).

Arrays in Java store one of two things: either primitive values (int, char, ...) or references (a.k.a pointers).

因此,new Integer[10] 仅为 10 个 Integer 引用创建空间.它不会创建 10 个 Integer 对象(甚至是 10 个 Integer 对象的可用空间).

So, new Integer[10] creates space for 10 Integer references only. It does not create 10 Integer objects (or even free space for 10 Integer objects).

顺便说一句,这与字段、变量和方法/构造函数参数的工作方式完全相同:它们也只存储原始值或引用.

Incidentally that's exactly the same way that fields, variables and method/constructor parameters work: they too only store primitive values or references.

这篇关于Java 中的数组及其在内存中的存储方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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