如何在数组比较中使用switch?

How to use switch in array comparison?

我想将数组长度与某些 int 值进行比较。我可以用 if else 来做,但是如何用 switch 来做,因为 switch 很快,我想在我的项目中使用它

switch (array.length) {
    case array.length <= 11: // how to do this 
        break;
    default:
        break;
}

有了 if else 我可以做到:

if (array.length <= 5) { 
    //my is code here 
}
else if (array.length <= 15) {
    //my is code here 
}
else if (array.length <= 10) {
    //my is code here 
}

switchif (...) { ... } else { ... } 不同。您只能在 case 中使用 ==。你必须做这样的事情:

int length = array.length;
switch (length) {
    case 0:
    case 1:
    case 2:
    [...]
    case 11:
        // your code here
        break;
    //other cases here
}

注意缺少的 break 语句,它们非常重要。 我建议 this tutorial 了解更多详情。

你不能。 switch 只能测试精确值。

你可以这样做:

switch(array.length) {
case 0: case 1: case 2: case 3:
case 4: case 5: case 6: case 7:
case 8: case 9: case 10: case 11:
    // do stuff
    break;
default:
    break;
}

但是为什么你要这样做?是什么让您认为它更快?

您不能使用 switch 来完成(根据您的示例)。由于 case 的值是常量表达式 (case *value*).

Switch 语句通过精确匹配而不是像 if 那样的比较来操作。你可以像这样引入一个新变量来做你想做的事:

int value = (array.length <= 11 ? 0 : (array.length <= 20 ? 1 : 2));
switch (value) {
    case 0:  // 11 or under
    break;
    case 1:  // 12 to 20
    break;
    case 2:  // 21 or more
    break;
}

我不知道这是否比 if/else 语句更能给你带来好处,但如果你觉得代码更清晰,你可以这样做。

在您的 if/elseif 中,if(array.length<=10) 永远不会 运行 因为如果 (array.length<=15) 在其上方被选中。

使用 if/elseif 结构执行此操作将需要更少的代码行。 如果您想使用 switch/case 语句执行此操作,则可以使用:

int length = array.length;

    switch(length) {
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5: {
        System.out.println("Case 0<=length<=5 triggered.");
        break;
    }
    case 6:
    case 7:
    case 8:
    case 9:
    case 10: {
        System.out.println("Case 6<=length<=10 triggered.");
        break;
    }
    case 11:
    case 12:
    case 13:
    case 14:
    case 15: {
        System.out.println("Case 10<=length<=15 triggered.");
        break;
    }
    default: {
        System.out.println("Default case triggered.");
    }
    }