为什么你的 switch 语句数据类型不能很长,Java?

人气:1,033 发布:2022-10-16 标签: java switch-statement language-design long-integer

问题描述

以下是 Sun 的 Java 教程的摘录:p>

开关适用于 byteshortcharint 原始数据类型.它也适用于枚举类型(在类和继承中讨论)和一些包装"某些原始类型的特殊类:CharacterByteShortInteger(在简单数据对象中讨论).

long 原始数据类型不允许使用一定有充分的理由.有人知道是什么吗?

解决方案

我认为在某种程度上这可能是基于 switch 的典型使用的任意决定.

一个 switch 本质上可以通过两种方式实现(或者原则上是一种组合):对于少数情况,或者值分布广泛的情况,一个 switch 本质上相当于一个临时的一系列 if变量(被打开的值只能被评估一次).对于数值上或多或少连续的中等数量的情况,使用一个切换表(Java 中的 TABLESWITCH 指令),从而有效地在表中查找要跳转到的位置.

这些方法中的任何一种原则上都可以使用长值而不是整数.但我认为这可能只是一个实际的决定,以平衡指令集和编译器的复杂性与实际需要:真正需要切换 long 的情况非常少见,以至于不得不重写为可接受的一系列 IF 语句,或以其他方式工作(如果有问题的 long 值非常接近,您可以在 Java 代码中切换 int 结果减去最小值).

Here's an excerpt from Sun's Java tutorials:

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects).

There must be a good reason why the long primitive data type is not allowed. Anyone know what it is?

解决方案

I think to some extent it was probably an arbitrary decision based on typical use of switch.

A switch can essentially be implemented in two ways (or in principle, a combination): for a small number of cases, or ones whose values are widely dispersed, a switch essentially becomes the equivalent of a series of ifs on a temporary variable (the value being switched on must only be evaluated once). For a moderate number of cases that are more or less consecutive in value, a switch table is used (the TABLESWITCH instruction in Java), whereby the location to jump to is effectively looked up in a table.

Either of these methods could in principle use a long value rather than an integer. But I think it was probably just a practical decision to balance up the complexity of the instruction set and compiler with actual need: the cases where you really need to switch over a long are rare enough that it's acceptable to have to re-write as a series of IF statements, or work round in some other way (if the long values in question are close together, you can in your Java code switch over the int result of subtracting the lowest value).

422