打开一对`int`s [英] Switching on a pair of `int`s

查看:34
本文介绍了打开一对`int`s的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些上下文:我正在解析一个具有 account1account2 作为 int 类型的会计分类帐.每个都是 [0, 99999] 范围内的数字.我有很多组合需要考虑.

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*/
}

等等.(我只需要考虑大约 20 种可能的组合).

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

有没有办法在 Java 中实现这一点?

Is there a way I can achieve this in Java?

我已经考虑过这个问题在 java 中存储数字对

并且可以构建一个IntPair类.也许如果我定义 bool equals 那么我可以在一个实例上 switch,以类似的方式你可以打开 java.lang.String.

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.

推荐答案

可惜这在 Java 中是不可能的.您只能打开整数类型, Java 版本 7 中的 java.lang.String.(您不能通过覆盖 equalshashCode 来自 java.lang.Object).

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.

这篇关于打开一对`int`s的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆