为什么你的switch语句数据类型不能长,Java? [英] Why can't your switch statement data type be long, Java?

查看:109
本文介绍了为什么你的switch语句数据类型不能长,Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


开关使用字节 char int 原始数据类型。它也适用于枚举类型(在类和继承中讨论)和一些包装某些基本类型的特殊类: Character Byte 整数(在简单数据对象中讨论)。


必须有充分的理由说明不允许使用 long 原始数据类型。有谁知道它是什么?

解决方案

我认为在某种程度上它可能是基于典型切换使用的任意决定。 / p>

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



这两种方法中的任何一种原则上都可以使用长值而不是整数。但我认为这可能只是一个实际的决定来平衡指令集和编译器的复杂性与实际需要:你真正需要切换很长时间的情况很少见,因此必须重新编写为一系列的IF语句,或以其他方式解决(如果有问题的长值靠得很近,你可以在你的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).

这篇关于为什么你的switch语句数据类型不能长,Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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