John Daniels
John Daniels

Reputation: 67

Error while using ternary operator

I'm writing my Code with Eclipse Juno and I'm using a hash table to set my dataImportObject depending on the entries in it. Could anyone please tell me whats wrong about this: ht is my hashTable with <String, Integer> pairs in it

(ht.containsKey("DEVICE_ADDRESS")) ? 
    dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]) : 
    dataImportObject.setDevice_Address("");

Upvotes: 3

Views: 619

Answers (2)

devBinnooh
devBinnooh

Reputation: 611

You can't set the return type of ternary condition to void.

Use if else for that.

Possible duplicate

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500375

Could anyone please tell me whats wrong about this

Two things:

  • The conditional operator can't be used as a statement on its own, only as an expression
  • I assume these set methods have void return types, so they can't appear as operands in the conditional operator

Three options:

  1. Use an if statement:

    if (ht.containsKey("DEVICE_ADDRESS")) {
         dataImportObject.setDevice_Address(dataitems[ht.get("DEVICE_ADDRESS")]));
    } else {
         dataImportObject.setDevice_Address("");
    }
    
  2. Use the conditional operator inside the setDevice_Address call, or even clearer, beforehand:

    String address = ht.containsKey("DEVICE_ADDRESS") 
        ? dataitems[ht.get("DEVICE_ADDRESS")] : "";
    dataImportObject.setDevice_Address(address);
    
  3. If you know that your hashtable won't have any null values, you can avoid the double lookup:

    Integer index = ht.get("DEVICE_ADDRESS");
    String address = index == null ? "" : dataitems[index];
    dataImportObject.setDevice_Address(address);
    

Upvotes: 16

Related Questions