当s1 = new Student()和s2 = new Student()时,如何更改Student类,使s1 == s2返回true? - java

在我的一次采访中,一名面试官问我:

给定一个Student类和两个对象s1s2

s1 = new Student();
s2 = new Student();

s1 == s2如何返回true

我告诉他让Student类成为一个单例,但他说不,我们必须更改类级别,以便s1 == s2返回true

注意:我们需要更改Student类。请不要回复s1=s2
有什么线索吗?

参考方案

这是一个技巧,但可以满足要求:

更改Student构造函数以引发一些异常(我选择了未经检查的异常,因此不必在throws子句中指定它):

public Student()
{
    throw new NullPointerException();
}

现在,假设我们被允许添加一个try-catch块:

Student s1 = null;
Student s2 = null;
try {
    s1 = new Student(); 
    s2 = new Student();
}
catch (Exception e) {
}
System.out.println (s1==s2);

由于trues1均为s2,因此将打印null

即使我们没有捕获到异常,在两次构造函数调用之后(实际上是在第一次构造函数调用之后,因为将永远不会执行第二个构造函数),s1 == s2仍然为true,但是我们必须按顺序在某个地方捕获异常测试一下。

这种方法如何运作? - java

我经常遇到这种注册动作侦听器的方法。尽管我最近一直在使用这种方法,但是我不明白这种方法的作用和原因这是一个:{submit=new JButton("submit"); submit.addActionListener(new ActionListener(){ // line 1 public void actionPerformed(…

SimpleDateFormat格式错误的值 - java

如下代码:SimpleDateFormat sdf = new SimpleDateFormat("MM/dd"); System.out.println(sdf.format(new Date(1293253200))); // 12/25/2010 05:00 GMT System.out.println(sdf.format(new…

Java易变变量 - java

我正在尝试通过以下示例了解易失用法。我希望它先打印10,然后再打印15。但是大多数时候,我最终会得到10和10。下面的代码本身是有问题的。class T implements Runnable { private volatile int x = 10; @Override public void run() { if(x==10) { System.out…

冬眠的工作。每次都要使用交易吗?如果我在重新绑定数据时不使用它,会引起任何问题吗? - java

我写了下面的代码来从数据库中检索数据,那我们需要开始事务吗?因为它运行没有任何问题。是否有必要每次使用?如果不这样做,将来会不会引起任何问题?public static Student getStudentById(long id) { Session session = null; Student student = null; //Transaction…

我正在尝试从用户那里获取输入并将其传输到文本文件 - java

我正在尝试编写一个聊天机器人,以便从用户那里学到答案,为此,我需要将答案保存到一个文本文件中,稍后再阅读。在代码中,它允许我编写问题,然后不创建文本文件并给出错误。有人可以告诉我我在做什么错。谢谢所有帮助。public static void main(String[] args) { // TODO Auto-generated method stub S…