I’m trying to write a piece of code that takes in a two digit hex number, e.g. “0C”, and compares it to a list.
I’m using Java 6 so can’t switch on a string and was initially planning on using switch on Enums but didn’t realise that Enums have to start with a letter.
Is there a simple way to achieve something like the following without a whole series of “if, else if…” statements?:
public void code(String oc) {
switch (oc) {
case 00:
// do something
break;
case 0A:
// do something else
break;
case A1:
....
}
Thanks,
Robert.
In Java 6, it is not possible to do this directly. You have to convert the String values to numbers (somehow), and then switch on the numbers. For instance:
The string to number conversion is relatively expensive, and probably negates the performance benefit of using a
switch… unless you have a large number of distinct cases.