简体   繁体   English

当我们在java中创建Integer类的实例时会发生什么

[英]What happens when we create instance of Integer class in java

I have a confusion regarding the following code:我对以下代码感到困惑:

import java.util.*;

public class HelloWorld {
    private int x;
    public HelloWorld(int x) {
       this.x = x;
    }
    public static void main(String[] args) {
       HelloWorld o1 = new HelloWorld(5);
       HelloWorld o2 = new HelloWorld(5);
       System.out.println(o1);
       System.out.println(o2);
       Integer i = new Integer(1);
       Integer j = new Integer(10);
       System.out.println(i);
       System.out.println(j);
    } 
}

Clearly, I made two objects of HelloWorld class and two objects of Integer class.显然,我创建了两个 HelloWorld 类对象和两个 Integer 类对象。 When I print them the output is like:当我打印它们时,输出如下:

HelloWorld@6d06d69c
HelloWorld@7852e922
1
10

My doubt is when I created Object of helloWorld class the objects store some references but when I create instance of Integer class, the values are stored in objects.我的疑问是当我创建 helloWorld 类的对象时,对象存储了一些引用,但是当我创建 Integer 类的实例时,这些值存储在对象中。 Why is this happening.为什么会发生这种情况。

Is there a way to directly store values in HelloWorld class objects also.有没有办法直接在 HelloWorld 类对象中存储值。

I have also noticed that whenever I create objects for any inbuilt class in java like String, Character, List, Map... they all store values.我还注意到,每当我为 Java 中的任何内置类(如 String、Character、List、Map……)创建对象时,它们都存储值。 So what is that present additionally in these inbuilt classes.那么这些内置类中另外存在的是什么。

My doubt is when I created Object of helloWorld class the objects store some references but when I create instance of Integer class, the values are stored in objects.我的疑问是当我创建 helloWorld 类的对象时,对象存储了一些引用,但是当我创建 Integer 类的实例时,这些值存储在对象中。

No, the value is being stored as a field within the instance (of HelloWorld or Integer ) in both cases.不,在这两种情况下,该值都存储为实例( HelloWorldInteger )中的字段。

Is there a way to directly store values in HelloWorld class objects also.有没有办法直接在 HelloWorld 类对象中存储值。

That's what your code does.这就是你的代码所做的。

If you want to change how instances of your HelloWorld class are converted to string, override toString .如果要更改HelloWorld类的实例转换为字符串的方式,请覆盖toString For instance:例如:

@Override
public String toString() {
    return String.valueOf(this.x);
}

The output you're seeing now is the output of the default toString from Object .您现在看到的输出是来自Object的默认toString的输出。

Java's compiler supports autoboxing and unboxing for primitives and wrapper classes. Java 的编译器支持对原语和包装类进行自动装箱和拆箱。

You can read about it here .你可以在这里阅读它。

In your example, method println expects int , which is primitive.在您的示例中,方法println需要int ,这是原始的。 So compiler automatically unboxes it from Integer .所以编译器会自动将它从Integer拆箱。

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

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