在我的一次面试中,一位面试官问我:
给定一个Student类和两个对象s1和s2:
s1 = new Student();
s2 = new Student();s1 == s2将如何返回true
我告诉他让Student类成为单例,但他拒绝了,我们必须改变类的级别,这样s1 == s2才能返回true。
注意:我们需要更改Student类。请不要回复s1=s2。有什么线索吗?
发布于 2018-06-01 03:10:21
这是一种技巧,但将满足要求:
更改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);这将打印true,因为s1和s2都是null。
即使我们没有捕获到异常,在两次构造函数调用之后(实际上是在第一次构造函数调用之后,因为第二次调用永远不会被执行),s1 == s2仍然是真的,但是我们必须在某个地方捕获异常以便对其进行测试。
发布于 2018-05-31 21:27:14
我看到的唯一合乎逻辑的解决方案是琐碎的:
s1 = new Student();
s2 = new Student();
s1=null;
s2=null;
System.out.println(s1==s2);或者:
s1 = new Student();
s2 = new Student();
s1=s2;
System.out.println(s1==s2);或者:
s1 = new Student();
s2 = new Student();
s2=s1;
System.out.println(s1==s2);正如@user7在评论中所建议的那样
发布于 2018-05-31 21:22:47
当==运算符比较对象引用时,我认为s1和s2必须为空。
https://stackoverflow.com/questions/50625203
复制相似问题