我正在用Eclipse Juno编写我的代码,我正在使用哈希表来设置我的dataImportObject,具体取决于其中的条目.
谁能告诉我这是错的:
ht是我的hashTable,其中< String,Integer>配对
谁能告诉我这是错的:
ht是我的hashTable,其中< String,Integer>配对
(ht.containsKey("DEVICE_ADDRESS")) ?
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) :
dataImportObject.setDevice_Address("");
最佳答案
Could anyone please tell me whats wrong about this
两件事情:
>条件运算符不能单独用作语句,仅作为表达式使用
>我假设这些set方法具有void返回类型,因此它们不能在条件运算符中显示为操作数
三种选择:
>使用if语句:
if (ht.containsKey("DEVICE_ADDRESS")) {
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]));
} else {
dataImportObject.setDevice_Address("");
}
>事先在setDevice_Address调用中使用条件运算符,甚至更清晰:
String address = ht.containsKey("DEVICE_ADDRESS")
? dataitems[ht.get("DEVICE_ADDRESS")] : "";
dataImportObject.setDevice_Address(address);
>如果您知道哈希表没有任何空值,则可以避免双重查找:
Integer index = ht.get("DEVICE_ADDRESS");
String address = index == null ? "" : dataitems[index];
dataImportObject.setDevice_Address(address);
相关文章
转载注明原文:java – 使用三元运算符时出错 - 代码日志