如何根据 Java 中 ArrayList 的大小将 char 分配给变量?

how to assign a char to an variable on the base of the size of an ArrayList in Java?

我试着让一个长的if语句更紧凑;原来是这样的:

char x;
if(list.size()== 1){
    x = 'a';
}
if(list.size()== 2){
    x = 'b';
}
if(list.size() == 3){
    x = 'c';
}
if(list.size() == 4){
    x= 'd';
}

是否可以压缩此代码?

已经谢谢了, 贾里范 M

更简单的选项: 使用 switch case.

骗子选项:

char x = (char) ('a' + list.size() - 1);

你基本上是将大小映射到一个字符。它可以更容易地完成:

x = 'a' + list.size() - 1;

作为第一步,我们将代码重构为 if-else 级联并备份我们将经常使用的列表大小:

1:

int size = list.size();
char x;
if(size == 1) {
    x = 'a';
} else if(size == 2) {
    x = 'b';
} else if(size == 3) {
    x = 'c';
} else if(size == 4) {
    x = 'd';
} else {
    //undefined
    x = '[=10=]';
}

由于我们只是在这种情况下将列表大小与常量进行比较,我们可以进一步将其转换为 switch 语句:

2:

char x;
switch (list.size()) {
    case 1: x = 'a'; break;
    case 2: x = 'b'; break;
    case 3: x = 'c'; break;
    case 4: x = 'd'; break;
    //undefined
    default: x = '[=11=]'; break;
}

假设这不是随机选择的示例而是真实代码,我们看到我们需要一个函数,它接受从 1 开始的数字,输出字母表('a''z') 增加值:

3:

char x;
if(list.isEmpty()) {
    //undefined
    x = '[=12=]';
} else {
    //our function
    x = (char) ('a' + list.size() - 1);
    if(x > 'z') {
        //undefined
        x = '[=12=]';
    }
}
char x;
int size = list.size();
if (size >= 1 && size <= 4) {
    x = "zabcd".charAt(size); 
}