gpt4 book ai didi

java - 为用户创建的类和 Java 中已存在的类创建对象数组之间的区别

转载 作者:行者123 更新时间:2023-12-01 09:59:33 26 4
gpt4 key购买 nike

我是从this得知的stackoverflow问题,代码

                     test1[] t = new test1[2];

在下面的程序中

class test1{
public int n;
void set(int n1){
n=n1;
}
}
class test{
public static void main(String arg[]){
test1[] t = new test1[2];
for(int i=0;i<2;i++)
t[i] = new test1();
t[0].set(12);
t[1].set(13);
for(int i=0;i<2;i++)
System.out.println(t[i].n);
}
}

需要初始化test1类的对象数组,并尝试在没有代码的情况下访问对象:

for(int i=0;i<2;i++)
t[i] = new test1();

抛出以下错误:

Exception in thread "main" java.lang.NullPointerException
at test.main(test1.java:12)

但我也尝试执行以下程序:

class test{
public static void main(String args[]){
Integer[] n = new Integer[2];
n[0] = 9;
n[1] = 18;
for(int i=0;i<2;i++){
byte b = n[i].byteValue();
System.out.println(b);
}
}

尽管我没有使用以下代码初始化 Integer 类的对象数组,但似乎工作没有任何错误:

for(int i=0;i<2;i++)
n[i] = new Integer();

在这种情况下,Integer类的对象数组和我创建的类的对象数组不同,这是怎么回事。

是否是我创建的的对象需要初始化,而Integer类的对象不需要初始化。我做对了吗?我只是想知道用户创建的类<​​/strong>和已经存在的类有何不同。

最佳答案

I have not initialized the array of object of the Integer class, using the code :

是的,您确实初始化了数组n的内容。就像任何引用数组一样,Integer[] 使用所有 null 进行初始化。

但是,您确实提供了值:

n[0] = 9;
n[1] = 18;

您只是没有使用 new,因为 Java 会将 int 文字自动装箱为 Integer 对象。您正在存储与 918 对应的 Integer 对象。

对象是否用于您创建的类并不重要。是否对 Java 的原始值使用“包装”类型很重要。您始终可以将 Java 自动装箱原始值放入包装类型中,例如intInteger

JLS, Section 5.1.7 ,列出所有可能的拳击转换:

  • From type boolean to type Boolean

  • From type byte to type Byte

  • From type short to type Short

  • From type char to type Character

  • From type int to type Integer

  • From type long to type Long

  • From type float to type Float

  • From type double to type Double

  • From the null type to the null type

关于java - 为用户创建的类和 Java 中已存在的类创建对象数组之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36922991/

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