Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as the options for a switch statment

I remember from way back at university using a switch with 'binary search' or 'binary switch'. Something like that, My google foo is broken today. Anyway it goes down like this: You define an array of possible options (Strings usually), some magic happens, and those options in the array become the cases in the switch happens. I do remember that they had to be in alphabetical order for this to work. Can you help me remember the magic? Even a name of what I should be looking at would be fantastic.

like image 302
Doug Miller Avatar asked Apr 08 '26 05:04

Doug Miller


2 Answers

I think what you are looking for is an Enum.

From the link above...

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

public class EnumTest {

    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
         switch (day) {
            case MONDAY:
                 System.out.println("Mondays are bad.");
                 break;

            case FRIDAY:
                 System.out.println("Fridays are better.");
                 break;

            case SATURDAY:
            case SUNDAY:
                 System.out.println("Weekends are best.");
                 break;

            default:
                 System.out.println("Midweek days are so-so.");
                 break;
        }
    }

    ....
}
like image 120
tvanfosson Avatar answered Apr 10 '26 19:04

tvanfosson


Did you mean gperf? Or possibly you were referring to the theory (hashing) in general?

http://www.gnu.org/software/gperf/

like image 33
HUAGHAGUAH Avatar answered Apr 10 '26 19:04

HUAGHAGUAH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!