简体   繁体   English

java原始类型数组对象与否?

[英]java primitive type array object or not?

Consider the following program:考虑以下程序:

int[] arr= new int[2];
.....
System.out.println(arr.length);

In JLS we read that object in java is instance of class or array.在 JLS 中,我们读取 java 中的对象是类或数组的实例。 But, we see here array of primitive type.但是,我们在这里看到原始类型的数组。 So, int[2] is an object too.所以, int[2]也是一个对象。 But, how it was achieved?但是,它是如何实现的呢? It was sth like int=>Integer , or int[]=>Integer[] or something else?有点像int=>Integerint[]=>Integer[]或其他什么? And by the way, where it resides?顺便说一下,它住在哪里? In heap or in stack?在堆中还是在堆栈中?

In Java you only have primitive or references to objects.*在 Java 中,您只有原始对象或对对象的引用。*

int[] arr = { 1, 2 };
int i = arr[0];
assert arr instanceof Object; // true

arr is a reference to an array which has int as a element. arr是对以int为元素的数组的引用。

how it was achieved?它是如何实现的?

int[] has it's own class int[].class and your arr is an instance of that class. int[]有它自己的类int[].class并且你的arr是该类的一个实例。

It was sth like int=>Integer, or int[]=>Integer[] or something else?它就像 int=>Integer 或 int[]=>Integer[] 或其他什么?

Integer is not related at all. Integer根本不相关。 to convert an int[] into an Integer[] you have to create a new array and copy every element one by one.要将int[]转换为Integer[]您必须创建一个新数组并一一复制每个元素。

And by the way, where it resides?顺便说一下,它住在哪里? In heap or in stack?在堆中还是在堆栈中?

You can assume all objects are on the heap.您可以假设所有对象都在堆上。 Java 8 can place some objects on the stack using Escape Analysis, however I don't believe it can do this for array types. Java 8 可以使用转义分析将一些对象放在堆栈上,但是我不相信它可以为数组类型做到这一点。

* the only other type is void which is neither a primitive nor a reference. *唯一的其他类型是void ,它既不是原始类型也不是引用。 It has a wrapper Void but you can't have a field or parameter of type void .它有一个包装器Void但你不能有一个void类型的字段或参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM