Java 数组中的长度是如何实现的? [英] How is length implemented in Java Arrays?

查看:24
本文介绍了Java 数组中的长度是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Java 数组的 length 的实现.我知道使用 arrayName.length 为我们提供了数组中元素的数量,但想知道这是一个方法/函数还是只是 Array 的数据成员?

I was wondering about the implementation of length of a Java Array. I know that using arrayName.length gives us the number of elements in the array, but was wondering if this is a method / function or it is just a data member of Array?

我猜它必须是一个数据成员,因为我们在调用它时不使用括号().但是如果它是一个数据成员,如何/何时分配/计算这个length的值?

I guess it must be a data member as we do not use parenthesis() when invoking it. But if it is a data member how/when is the value of this length assigned/computed?

推荐答案

根据 Java 语言规范(特别是 §10.7 数组成员) 它是一个字段:

According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

  • public final 字段length,其中包含数组的组件数(长度可以是正数或零).
  • The public final field length, which contains the number of components of the array (length may be positive or zero).

在内部,该值可能存储在对象头中的某处,但这是一个实现细节,取决于具体的 JVM 实现.

Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

HotSpot VM(流行的 Oracle(以前称为 Sun)JRE/JDK 中的那个)存储对象头中的大小:

The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

[...] 数组有第三个头字段,用于数组大小.

[...] arrays have a third header field, for the array size.

这篇关于Java 数组中的长度是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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