Java:构造函数中的NULL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26211744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:30:14  来源:igfitidea点击:

Java: NULL in constructor

javaconstructornullpointerexception

提问by Lisa Anne

Please I have this question which is a bit theoretical, but I would like to understand it.

请我有这个有点理论化的问题,但我想了解它。

Why if I pass a null argument to a constructor do I get a NullPointerException?

为什么如果我将空参数传递给构造函数,我会得到一个NullPointerException?

This is my example

这是我的例子

new AttendeeDetail("Gus Goose","1151","15-01-2012",(Integer) null,null) 

This is the class:

这是课程:

public class AttendeeDetail {

    private String ticketholder_name;
    private String user_id;
    private String date_of_birth;
    private int tickets_purchased;
    private ArrayList<Ticket> tickets;

    public AttendeeDetail(String ticketholder_name, String user_id, 
        String date_of_birth, int tickets_purchased, ArrayList<Ticket> tickets) 
    {
        this.ticketholder_name=ticketholder_name;
        this.user_id=user_id;
        this.date_of_birth=date_of_birth;
        this.tickets_purchased=tickets_purchased;
        this.tickets=tickets;
    }
}

采纳答案by jhamon

an intcan't be null. If you really need to pass a null value, use the Integertype

一个int不能null。如果确实需要传递空值,请使用Integer类型

回答by weston

You're assigning an Integer: (Integer) nullto an intparameter: int tickets_purchased.

你分配一个Integer(Integer) null一个int参数:int tickets_purchased

Integer, as a reference type can be null, but intas a primitive type cannot be, so an error occurs during the attempt to convert.

Integer,作为引用类型可以null,但int作为基本类型不能,所以在尝试转换的过程中会发生错误。

This conversion is called an unboxing operation.

这种转换称为拆箱操作

回答by izstas

Consider the following code:

考虑以下代码:

public class Main {
    public static void main(String[] args) {
        Integer wrapped = null;
        int primitive = wrapped;
    }
}

Now, let's see what this code compiles to by using javap:

现在,让我们看看这段代码编译成什么javap

public static void main(java.lang.String[]);
Code:
   0: aconst_null
   1: astore_1
   2: aload_1
   3: invokevirtual #2                  // Method java/lang/Integer.intValue:()I
   6: istore_2
   7: return

As you can see, in order to unbox the Integerit tries to invoke Integer#intValue()method on nullreference, and therefore it throws NullPointerException.

如您所见,为了取消装箱,Integer它尝试在引用Integer#intValue()上调用方法null,因此它抛出NullPointerException.

回答by Stephen C

As other answers mention, the problem is this - (Integer) null.

正如其他答案所提到的,问题是 - (Integer) null

When the formal type of a method argument is intand you try to pass (Integer) null, the following is going to happen.

当方法参数的正式类型是int并且您尝试传递时(Integer) null,将发生以下情况。

  1. The Java compiler is going to say "Ah! I have an Integervalue, and I need to convert it to an intvalue. I will output code to unboxit!".

  2. The code to unbox the value is a call to Integer.intValue(), using the value-to-be-unboxed as the target object. Except that the value is null... not a real object reference.

  3. At runtime, you end up calling intValue()on the null, and that throws an NPE.

  1. Java 编译器会说“啊!我有一个Integer值,我需要把它转换成一个int值。我会输出代码来拆箱它!” .

  2. Integer.intValue()取消装箱值的代码是对 的调用,使用要取消装箱的值作为目标对象。除了值是null...不是真正的对象引用。

  3. 在运行时,你最终调用intValue()null,而且抛出NPE。

Some compilers will issue a warning for this, saying that the code will always throw an NPE. However, this is legal Java code, so a conformant Java compiler cannot call this a compilation error.

一些编译器会为此发出警告,说代码总是会抛出 NPE。但是,这是合法的 Java 代码,因此符合标准的 Java 编译器不能将其称为编译错误。



Possible solutions:

可能的解决方案:

  1. Don't use (Integer) nullas the parameter. Pass an intvalue, or an actual (not null) Integerobject. In this case, zero looks like a reasonable substitute.

  2. Change the type of the formal parameter from intto Integer... and propagate the change to the places where the corresponding field value is returned, used, etcetera.

  1. 不要(Integer) null用作参数。传递一个int值或一个实际的(非空)Integer对象。在这种情况下,零看起来像是一个合理的替代品。

  2. 将形式参数的类型从更改intInteger... 并将更改传播到相应字段值的返回、使用等位置。

The first alternative is probably the correct one, unless you reallyneed to model the possibility that an "attendee" has purchased an unknownnumber of tickets. (And if you do need to model that, then your application has to cope with this possibility ... somehow.)

第一种选择可能是正确的,除非您确实需要模拟“与会者”购买了未知数量的门票的可能性。(如果您确实需要对此进行建模,那么您的应用程序必须以某种方式应对这种可能性。)

回答by Pienterekaak

Yes, you get a null pointer exception because Java will try to autobox your null Integer to an int, and that wont work since null ints are not allowed :) (since you already tried it out i thought id give an explenation why you see this behaviour)

是的,您会收到空指针异常,因为 Java 会尝试将您的空整数自动装箱为 int,这将不起作用,因为不允许使用空整数:)(因为您已经尝试过了,我想我会给出一个解释,为什么您会看到这个行为)

回答by Vikas Verma

int tickets_purchased = (Integer)null;this is not allowed in java.

int tickets_purchased = (Integer)null;这在java中是不允许的。

You can use Integer tickets_purchased = (Integer)null;

您可以使用 Integer tickets_purchased = (Integer)null;