Object 中声明的方法的一个问题是在它们的使用中缺少静态类型检查。这同样适用于同步,通常会锁定错误的对象。
在这种情况下 Object.equals(Object) 适用于任何两个对象。您已经使用了集合、数据包,而不是从中获取元素。重要的问题不是这个特定的错误是如何产生的,而是我们如何从一开始就防止它发生。
首先,使用泛型并将迭代的每个元素分配给静态类型的本地:
public int countPacks(String flavour) {
// [ The field represents a count. ]
int count = 0;
for(int index=0; index<packets.size(); ++index) {
String packet = packets.get(index);
if (packet.equals(flavour)) {
++count;
}
}
// [The error mesage was printed for each non-match.
// Even this is probably wrong,
// as it should be valid to have no packs of a valid flavour.
// Having the message in this method is actually a bit confused.]
if (count == 0) {
System.out.println("You have not entered a correct flavour");
}
return count;
}
我们可以使用增强的 for 循环进一步整理。
public int countPacks(String flavour) {
int count = 0;
for(String packet : packets) {
if (packet.equals(flavour)) {
++count;
}
}
if (count == 0) {
System.out.println("You have not entered a correct flavour");
}
return count;
}
这看起来更清楚,但一个好的程序员知道他/她的库。
public int countPacks(String flavour) {
int count = Collections.frequency(packets, flavour);
if (count == 0) {
System.out.println("You have not entered a correct flavour");
}
return count;
}
您也可以考虑使用Map<String,Integer> 而不是集合。