4

I have an ArrayList which has the following Strings in it: [name, age, gender, salary]. Is there a way I can use the values in my ArrayList to be case expressions? The obvious answer would be no, since case expressions must be constant expressions. However, I am wondering what the best way to do this would be if I can't use switch/case.

To be clear, the intended behavior is something like this:

switch (parameter) {
    case XXX:
        // some code here
    case YYY:
        // some code here
}

I want XXX to be name, and YYY to be gender, which both come from the ArrayList. I'm open to using if/else if this can't be done with switch/case. How can I do something like this? Thanks.

user8543721
  • 43
  • 1
  • 2
  • 4

1 Answers1

3

If you really want to use a switch case and can't use non-native java objects, I would try something along the lines of this:

public void test(){

    String[] array = {"name", "age", "gender", "salary"};

    String value = "name";

    switch(indexOf(value, array)){
        case 0:
            //code
            break;
        case 1:
            //code
            break;
        case 2:
            //code
            break;    
        case 3:
            //code
            break;
        default:
            //value wasnt in array
    }
}

public int indexOf(String value, String[] array){
    for(int i = 0; i < array.length; i++){
        if(array[i].equals(value)){
            return i;
        }
    }
    //return a place holder value
    return -1;
}
luckydog32
  • 909
  • 6
  • 13
  • I like the approach. However, this is assuming that case 0 always maps to name, case 1 always maps to age, etc... right? – user8543721 Oct 12 '17 at 02:28
  • That is correct. A better way to handle this problem would be to make a person class with the attributes of name, age, gender, and salary. It gives you way more control over with how you want to handle each attribute. – luckydog32 Oct 12 '17 at 02:38
  • 1
    I cant comment on other peoples posts because my reputation is too low, but Hayden's solution won't compile because the Strings are still not a constant. – luckydog32 Oct 12 '17 at 02:45
  • What do you mean "not a constant"? – Hayden Passmore Oct 12 '17 at 05:35
  • 1
    Basically the values can change during run time, and that's not something java supports in a case switch. You can get around this by using the final keyword which will make it impossible to change the value of the variable. – luckydog32 Oct 12 '17 at 05:54
  • 1
    Ok thanks. I overlooked that as I was trying to provide a proof of concept. Nice spot :-) – Hayden Passmore Oct 12 '17 at 06:25
  • @Hayden Passmore It still wouldn't quite work with the last edit you made. Since you can't change the values of final variables you can't do something like `final String WWW = yourArrayList.get(0);` – luckydog32 Oct 13 '17 at 00:05