[英]Error while using ternary operator
我正在用Eclipse Juno编写我的代码,我正在使用哈希表来设置我的dataImportObject,具体取决于其中的条目。 任何人都可以告诉我这是错的: ht
是我的hashTable,其中包含<String, Integer>
对
(ht.containsKey("DEVICE_ADDRESS")) ?
dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) :
dataImportObject.setDevice_Address("");
有谁能告诉我这有什么不对
两件事情:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.