我们都知道StringJava 中是不可变的,但请检查以下代码:
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = s1.substring(6);
System.out.println(s1); // Hello World
System.out.println(s2); // Hello World
System.out.println(s3); // World
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[])field.get(s1);
value[6] = 'J';
value[7] = 'a';
value[8] = 'v';
value[9] = 'a';
value[10] = '!';
System.out.println(s1); // Hello Java!
System.out.println(s2); // Hello Java!
System.out.println(s3); // World
Run Code Online (Sandbox Code Playgroud)
为什么这个程序运行这样?为什么价值s1和s2变化,但不是s3?
今天在我的采访中,一位采访者让我写了一个Singleton课程.我给出了答案
public class Singleton {
private static Singleton ref;
private Singleton() {
}
public static Singleton getInstance() {
if (ref == null) {
ref = new Singleton();
}
return ref;
}
}
Run Code Online (Sandbox Code Playgroud)
突然他告诉我这是写作课的老方法.任何人都可以帮助我,为什么他这样说.
我选择使用属性文件来自定义某些设置.我使用以下代码在类中提供属性对象
Properties defaultProps = new Properties();
try {
FileInputStream in = new FileInputStream("custom.properties");
defaultProps.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
我是否必须将此添加到每个班级?可能不是因为那时每个类都会打开一个流到这个文件.但我不确定如何妥善处理这个问题.我应该创建一个类MyProperties并在任何类需要属性中实例化它吗?
提前致谢!
class test {
test() {
System.out.println("Constructor");
}
{
System.out.println("Hai");
}
}
public class sample {
public static void main(String [] a) {
test t = new test();
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,为什么在执行构造函数之前,在大括号((即)"Hai")中给出的语句是Printed.