简体   繁体   中英

How array of primitive types work in Java?

In java, It is said that "every thing instantiated other than primitive type is an object."

I am trying to understand this point using below code (line 4 to be specific).

public class dummy{
    public static void main(String[] args){
        int[] i = new int[2];
        i[0] = new Integer(3); //line 4
        i[1] = 3;
        System.out.println(int[].class);
        System.out.println(i[0]);
    }
}

After running

int[] i = new int[4];

Java is creating an object [0,0] of type class [I . The two members within this object [0,0] are primitive data type(but not reference type).

My questions:

  1. Why does Java allow assignment of an object to primitive type member as per below line?

     i[0] = new Integer(3); // object of type 'class Integer' getting assigned to i[0] 

    How do I understand this? In counter, i[0] displays value 3 but not object address.

  2. What is I in class [I ? I mean, for class C{}; , C[].class gives class [LC where [ means "array of" and LC means "instance of 'class C'"

i[0] = new Integer(3);

This involves what's known as auto-unboxing . In the Dark Ages of Java (pre-1.5) we used to have to explicitly box and unbox primitive types. But thankfully the language designers had pity on our poor fingers and added some syntactical sugar. They now let us convert freely between primitives and their wrapper types. Java secretly transforms the above code into this:

i[0] = new Integer(3).intValue();

That's auto-unboxing. Similarly, it will box values for you without your having to ask. If you write:

Integer i = 5;

Java will actually perform:

Integer i = Integer.valueOf(5);

What is I in class [I ?

That's I for int .

  1. Java is expecting you to assign an int to an element of the array, but you pass Integer , so it is automatically unboxed as int . By the way, when you create an Integer[] array, you will also get the same result when doing System.out.println , because Integer.toString just creating the string of it's value, not "object address".
  2. [ means one-dimensional array. I means int .

java/lang/Integer.intValue:()I is being called when you do i[0] = new Integer(3); //line 4 i[0] = new Integer(3); //line 4 ie, the compiler is implicitly getting the int value of the Integer and adding it in the array.

For your first question, Java autoboxes primitive types with their wrapper classes (for example, int gets wrapped into the Integer class) and also unboxes wrappers of primitive types.

Here is the documentation: http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

编译器执行基元与其对应对象之间的转换,以方便程序员。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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