Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching on a pair of `int`s

Some context: I'm parsing an accounting ledger which has account1 and account2 as int types. Each is a number in the range [0, 99999]. I have many combinations to consider.

Ideally I'd like to use something like

switch (account1, account2){
    case (1,1):
        /*account1 is 1, account2 is 1*/
    case (2,1):
        /*account1 is 2, account2 is 1*/
}

and so on. (I only need to consider about 20 possible combinations).

Is there a way I can achieve this in Java?

I've considered this question Storing number pairs in java

and could build an IntPair class. Perhaps if I define bool equals then I could switch on an instance, in a similar manner in which you can switch on java.lang.String.

like image 527
Michael Bullock Avatar asked Dec 10 '22 13:12

Michael Bullock


2 Answers

Alas this is not possible in Java. You can only switch on integral types, or a java.lang.String from Java version 7. (You can't build this functionality into your own type by overriding equals and hashCode from java.lang.Object).

But that could inspire you to make a hack:

switch (Integer.toString(account1) + "_" + Integer.toString(account2)){
    case "1_1":
    case "2_1":    
}

I find this to be surprisingly readable.

like image 123
Bathsheba Avatar answered Dec 27 '22 13:12

Bathsheba


EDIT :

Maybe this ?

public enum Account{

    ACC_512_401(512,401), 
    ACC_512_402(512,402);

    private final int accA;
    private final int accB;

    Account(int accA, int accB){
        this.accA=accA;
        this.accB=accB;
    }

    private int getAccA(){
        return accA;
    }
    private int getAccB(){
        return accB;
    }
    public static Account getEnum(int accA, int accB){
        for(Account acc : values()){
            if(accA == acc.getAccA() && accB == acc.getAccB()){
                return acc;
            }
        }
        return null;
    }
}



public class testswitch {
    public static void main(String[] args) {
        test(Account.getEnum(512, 401));
    }

    public static void test(Account acc){

        switch (acc){
        case ACC_512_401:
            System.out.println("A");
            break;
        case ACC_512_402:
            System.out.println("A");
            break;
            default:
                break;
        }
    }
}

You do your switch over your enum.

EDIT : I added getEnum method to get value for int input. Now it's what you want I guess.

like image 33
Morgan Avatar answered Dec 27 '22 13:12

Morgan