当我需要一串字符串,这俩种方法哪一种泛用性更高?
1:调用静态变量
public static final List<String> temp = new ArrayList<>();
static{
temp.add("test1");
temp.add("test2");
temp.add("test3");
}
2:调用方法
public static List<String> getTemp(){
List<String> temp = new ArrayList<>();
temp.add("test1");
temp.add("test2");
temp.add("test3");
return temp;
};
第一个呗称之为贪婪加载,也就是说无论有没有调用,都要执行一次这个代码(static块的本质是使用static的构造函数)
第二个称之为懒惰模式,只有在需要的时候才加载。
前者会增加程序内存消耗和首次启动的时间,但是好处是一次性加载了,程序运行的时候就很快了。
不知道你说的“泛用性”是什么意思?通用性?这个和通用性似乎没有什么关系。