我写了一个程序如下:

public class Testing {

    Student student;
    public static void main(String[] args) {
        Supplier<Student> myStudent = Student::new;
        Student stu = new Testing().computeRequiredValue(myStudent).get();

        System.out.println(myStudent == stu);

        System.out.println(stu.getId());
    }

    public Supplier<Student> computeRequiredValue(Supplier<Student> valueToBePopulated) {
        Optional<Student> studentOptional = Optional.ofNullable(valueToBePopulated.get());

        if (studentOptional.isPresent()) {
            student = valueToBePopulated.get();
            student.setId("22");
            student.setName("Dbanga Srinu");
        }

        return valueToBePopulated;

    }

}


我看到了System.out.println(myStudent == stu)的输出;

    System.out.println(stu.getId());


为false和null。我假设myStudent和stu引用同一对象,在堆上,应该对其进行修改,并且条件myStudent == stu应该返回true,而stu.getId()应该返回一个值。

请帮助理解这一点。

最佳答案

Supplier<Student>不是引用,也不是任何特定的Student,而是提供Student的函数。

这意味着myStudent == stu永远不会相等,因为它们不是同一类型。

由于Supplier<Student>不是函数,因此实际上您总共要调用.get() 3次,创建多个不同的Students,在您的字段中创建一个,在局部变量中创建一个。

尝试将您的computeRequiredValue函数更改为仅致电供应商一次,然后返回Optional学生。

public class Testing {

    static Student student; // changed this to be static so I can reference it in main
    public static void main(String[] args) {
        Supplier<Student> myStudent = Student::new;
        Student stu = new Testing().computeRequiredValue(myStudent).get();

        System.out.println(student == stu); // using the same types, this can now be true, assuming they are in fact the same instance

        System.out.println(stu.getId()); // prints 22
        System.out.println(student.getId()); // prints 22
    }

    public Optional<Student> computeRequiredValue(Supplier<Student> valueToBePopulated) {
        Optional<Student> studentOptional = Optional.ofNullable(valueToBePopulated.get());

        if (studentOptional.isPresent()) {
            student = studentOptional.get(); // get the optional, not calling the supplier again.
            student.setId("22");
            student.setName("Dbanga Srinu");
        }

        return studentOptional; // returns the optional
    }
}

07-24 19:59