Код: Выделить всё
public class FromTgSingletone {
private final List someList;
public List getSomeList() {
return new ArrayList(someList);
}
private FromTgSingletone() {
someList = new ArrayList(MySingletonHolder.someList);
}
public static FromTgSingletone getInstance() {
return MySingletonHolder.instance;
}
private static class MySingletonHolder {
private static final FromTgSingletone instance = new FromTgSingletone();
private static final List someList = new ArrayList(Arrays.asList("Hello", "world", "!"));
}
}
< /code>
Но если мы обмениваемся порядок инициирования в Mysingletonholder. Он работает < /p>
private static class MySingletonHolder {
private static final List someList = new ArrayList(Arrays.asList("Hello", "world", "!"));
private static final FromTgSingletone instance = new FromTgSingletone();
}
< /code>
Почему? Если мы добавим примитивный var после List init, он работает: < /p>
public class FromTgSingletone {
private final List someList;
public List getSomeList() {
return new ArrayList(someList);
}
private FromTgSingletone() {
System.out.println(MySingletonHolder.s); //works
someList = new ArrayList(MySingletonHolder.someList); //doesn't
}
public static FromTgSingletone getInstance() {
return MySingletonHolder.instance;
}
private static class MySingletonHolder {
private static final FromTgSingletone instance = new FromTgSingletone();
private static final List someList = new ArrayList(Arrays.asList("Hello", "world", "!"));
private static final int s = 99;
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... -important