【问题标题】:java method value 'null' assigned to Object is never used [duplicate]从未使用过分配给 Object 的 java 方法值 \'null\' [重复]
【发布时间】:2022-12-12 12:27:11
【问题描述】:

我在 java 中运行一个简单的测试:

public class LawAcademyInterview {

@Test
void question1() {
    Student student = new Student(1, "adam",99);
    System.out.println("Before set to null: "+student);
    makeItNull(student);
    System.out.println("After set to null: "+student);
    if (student == null)
        System.out.println("Student is null");
    else
        System.out.println("Student is NOT null");
}
public void makeItNull(Student student) {
    student = null; // Intellij warning: The value 'null' assigned to 'student' is never used
}

以下是输出:

Before set to null: Student(rollNo=1, name=adam, marks=99)
After set to null: Student(rollNo=1, name=adam, marks=99)
Student is NOT null

有趣的是当我这样做时:

 @Test
    void question2() {
        Student student = new Student(1, "adam", 99);
        System.out.println("Before set to null: " + student);
        student = null;
        System.out.println("After set to null: " + student);
        if (student == null)
            System.out.println("Student is null");
        else
            System.out.println("Student is NOT null");
    }

输出是:

Before set to null: Student(rollNo=1, name=adam, marks=99)
After set to null: null
Student is null

任何人都有一个很好的解释,因为这几天一直困扰着我。在面试高级开发人员角色时向我提出了这个问题。我知道,我感到羞耻...... :(

【问题讨论】:

  • student = null 在你的方法中意味着你的方法内部的学生变量不再指向你的方法之外的学生变量指向的引用。

标签: java null object-reference


【解决方案1】:

发生这种情况是因为 Java 按值而不是引用传递对象,因此为什么更改 makeItNull() 内部的变量 student 仅适用于该函数的范围内,它不会影响其他范围内的变量。

Java按值或引用传递解释: Is Java "pass-by-reference" or "pass-by-value"?

你可能想这样做:

public class LawAcademyInterview {

@Test
void question1() {
    Student student = new Student(1, "adam",99);
    System.out.println("Before set to null: "+student);
    student = makeItNull();
    System.out.println("After set to null: "+student);
    if (student == null)
        System.out.println("Student is null");
    else
        System.out.println("Student is NOT null");
}
public void makeItNull() {
    return null;
}

这相当于你的第二个代码,

student = null;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多