记录一下关于static关键字作为全局变量的作用。自己的理解,不知道对不对?
如果不对希望可以指正一下,thanks
static作为的全局变量可以共享,例如。
public class a {
public static void main(String[] args) {
Person p1 = Person.person();
p1.map.remove("11");
Person p2 = Person.person();
System.out.println(p1.map);
System.out.println(p2.map);
}
}
@Data
class Person {
public static Map<String, String> map = new HashMap<>();
private Integer age = 1;
static {
map.put("11","11");
}
public static Person person(){
return new Person();
}
}
这里打印的结果是:
{}
{}
new 两个对象,将其中一个对象的map给remove调了,另外一个对象也存在了。
对于非static修饰的,再创建对象时,是独立维护的。例如
public class a {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
p1.removeMap("11");
System.out.println(p1.map());
System.out.println(p2.map());
}
}
@Data
class Person{
private Map<String,String> map = new HashMap<>();
private Integer age=1;
public Person() {
map.put("11","11");
}
public Map<String,String> map(){
return map;
}
public void removeMap(String key){
map.remove(key);
}
}
这里打印的结果是:
{}
{11=11}
引用场景:对别人中的代码进行提取时,要判断原来的类是否是单例引用还是多例引用。要采取不同的处理手段。
单例:
多例: