gpt4 book ai didi

java - 如果int不继承Object,那为什么 "String.format(String, Object ...)"用int的编译呢?

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:47 25 4
gpt4 key购买 nike

我读了这篇文章:Is int an object in Java? .

在帖子中,争论的是int 不是从Object 继承的。如果是这样,那么为什么下面的代码编译没有任何错误?鉴于 int 不是 Object 并且 format() 方法的签名是 public static String format(String format, Object.. .args) 如文档所示:javadoc for String !

public class Testing {
public static void main(String[] args) {
int integer = 7;
String str = String.format("%03d", integer);
System.out.println(str);
}
}

我也读过“自动装箱”。这到底是什么意思?在编译之前,是否所有原语都被适当的 Object 替换了?如果是这样,那么在使用大型 int (int[]) 数组时,内存使用是否比 Integer ( 整数[])? double 等也有类似的论点。

欢迎任何见解。

最佳答案

它是由 Autoboxing 引起的.

这是链接的 Java 文档中的一小段,比我能更好地解释它:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Here is the simplest example of autoboxing:

Character ch = 'a';

The rest of the examples in this section use generics. If you are not yet familiar with the syntax of generics, see the Generics (Updated) lesson.

Consider the following code:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(i);

Although you add the int values as primitive types, rather than Integer objects, to li, the code compiles. Because li is a list of Integer objects, not a list of int values, you may wonder why the Java compiler does not issue a compile-time error. The compiler does not generate an error because it creates an Integer object from i and adds the object to li. Thus, the compiler converts the previous code to the following at runtime:

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i += 2)
li.add(Integer.valueOf(i));

关于java - 如果int不继承Object,那为什么 "String.format(String, Object ...)"用int的编译呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26190981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com