这是一道我无法完成的考试题。
How do you get the following java code to print false by only editing code within the MyClass constructor?
public class MyClass{ public MyClass(){ } public static void main(String[] args) { MyClass m = new MyClass(); System.out.println(m.equals(m)); } }
You are NOT allowed to override the equals method, or change any of the code within the main method. The code must run without the program crashing.
根据我的研究,实例化类时不能将 Java 对象引用设置为 null。所以我被正式难住了。
最佳答案
太难了!!
public MyClass() {
System.setOut(new PrintStream(new FilterOutputStream(System.out) {
@Override
public void write(byte[] b, int off, int len) throws IOException {
if(new String(b).contains("true")) {
byte[] text = "false".getBytes();
super.write(text, 0, text.length);
}
else {
super.write(b, off, len);
}
}
}, true));
}
或 Paul Boddington 的简化版:
PrintStream p = System.out;
System.setOut(new PrintStream(p) {
@Override
public void println(boolean b) {
p.println(false);
}
});
或者 AJ Neufeld 的更简单的建议:
System.setOut(new PrintStream(System.out) {
@Override
public void println(boolean b) {
super.println(false);
}
});
关于java - 使用类构造函数操作 Java 对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365618/