我有一段代码
for(int i = 0; i < num_of_random; i++){
String str = in.readLine();
if(str != null){
String[] randoms = new String[4];
randoms = str.split(",");
dateRanges[i] = Integer.parseInt(randoms[0]);
id[i] = Integer.parseInt(randoms[1]);
flag[i] = Integer.parseInt(randoms[2]);
system[i] = Integer.parseInt(randoms[3]);
}
}
当我对findBugs运行这段代码时,我得到了
的建议"String[] randomms = new String[4];"
该指令将一个值赋给一个局部变量,但该值不会被任何后续指令读取或使用。通常,这表示一个错误,因为计算的值永远不会被使用。
为什么我得到这个?
Thanks to lot
因为您将变量初始化为一个值(new String[4]
),然后将变量值替换为另一个值(str.split(",")
的结果)。因此不需要初始化。
你的代码在功能上等同于
String[] randoms = str.split(",");
,除非它分配一个新的String数组,该数组立即被丢弃。
因为你可以这样做:
String[] randoms = str.split(",");
直接尝试:
String[] randoms = str.split(",");
不需要实例化String[]
, split
方法已经实例化了
这是一个我称之为的技巧的例子。。
通常是程序员写代码,但不知道他们在做什么。程序员有时会读到或听到这样的话:"必须初始化所有局部变量!"当他们写代码String[] randoms
时,他们突然想到了= new String[4]
。