3

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("");
Peter Elliott
  • 3,273
  • 16
  • 30

2 Answers2

16

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);
    
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Yeah, that´s it. Seems like I've missunderstood the ternary operator ... I just wanted to use it to shorten my If statements, because I'm gonna need many of them but as my set functions return void, this won't work ... so I'll have to Use number 2. thanks very much – John Daniels Mar 12 '13 at 17:24
0

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

Use if else for that.

Possible duplicate

Community
  • 1
  • 1
devBinnooh
  • 611
  • 3
  • 12