说说java的数组

在the Java Language Specification 3rd里提到: 

IN the Java programming language arrays are objects, are dynamically created, and may be assigned to variables of type Object . All methods of
class Object may be invoked on an array.

Every array implements the interfaces Cloneable and java.io.Serializable.

 java里的数组在运行时会转成一个对象,该对象extends了Object并实现了Cloneable、java.io.Serializable接口。

在jkd的api文档的Class类说明里,提到:

每个数组属于被映射为 Class 对象的一个类,所有具有相同元素类型和维数的数组都共享该 Class 对象。

也同时印证了数组会在运行时转成一个代表数组类的对象。

JLP 3rd里同时提到:

The members of an array type are all of the following:The public final field length, which contains the number of components of the array (length may be positive or zero).

我们可以从中想象出数组类对象是怎样的。

比如:int intArray[ ] = new int[2];

int[2]在运行时可能会转化成以下形式:

Class IntArray {
   
int length;
   
int int0;
   
int int1;
}

可以用.length查到数据的对象里的元素个数。

这也是为何能写new byte[0]这种形式,它其实会转化成:

Class ByteArray{
   
int  length;
}

也样也很容易理解为何存用基本类型的数组初始化后里面的的元素值为默认值,而存用非基本类型的数组初始化后里面的的元素值null。

可能会问new byte[0],一个长度为0的数组有什么用呢?我会在另一篇文章再谈这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值