当前位置 : 主页 > 编程语言 > java >

聊聊Java的switch为什么不支持long

来源:互联网 收集:自由互联 发布时间:2021-11-19
目录 Java为什么不浪(long) 疑问 分析 编程思想汇总 switch能否作用于Long,string上 Java为什么不浪(long) 学而时习之不亦说乎,继续温习Java。 今天使用switch时,不小心写了如下代码,
目录
  • Java为什么不浪(long)
  • 疑问
  • 分析
  • 编程思想汇总
  • switch能否作用于Long,string上

Java为什么不浪(long)

学而时习之不亦说乎,继续温习Java。

今天使用switch时,不小心写了如下代码,报错如下。

 public static void main(String[] args) {
   long s = 20L;
   switch (s) {
   case 20L:
    System.out.println("haha");
    break;

   default:
    break;
   }
 }
/*
Cannot switch on a value of type long. Only convertible int values, strings or enum variables are permitted
*/

疑问

1.为什么可以支持byte、char、short、int,不能支持long呢?

2.为什么可支持enum和String?注意enum是JDK5引入,switch支持String是JDK7支持

分析

1.为什么可以支持byte、char、short、int,不能支持long呢?

发现一个共同点,这些都是基础数据类型中的整数,并且最大不超过int。正好去研究一下官方文档说明。

Compilation of switch statements uses the tableswitch and lookupswitch instructions.
The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets.
The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.
The Java Virtual Machine's tableswitch and lookupswitch instructions operate only on int data. Because operations on byte, char, or short values are internally promoted to int, a switch whose expression evaluates to one of those types is compiled as though it evaluated to type int.

意思是说switch的编译会用到两个指令,tablesswitch和lookupswitch。而这2个指令指令只会运行在int指令下,低于int的正数类型会被转为int类型,而这一点和short、byte等类型在计算时会被转为int来处理的表现是一致的。

到此为止,我们知道第一个问题的答案了。在编译时,switch被编译成对应的2个实现方式的指令,这2种指令只支持int类型。

2.为什么可支持enum和String?

按照网络资料反编译对照来看,enum最终也是转换为enum的int序号来适应switch的。而String类型要怎么和int对应起来呢,有一种方式叫hashcode计算,最后可以得出一个数值,把这个控制在int范围内,就能适应switch的要求了。

编程思想汇总

1.类比switch支持enum和String的实现。

在程序开发中,由于第三方库或者工具类中方法参数限制,调用者必须对参数做一些转换才能调用这些方法的情况下,我们可以使用适配器模式来抹平这种差异。

2.类比switch在JDK版本在5时引入enum的支持,在7时引入对String支持。

在程序开发中,版本迭代是最常见也是能够很好权衡开发速度和质量的方式。类似一个App程序,我们花2年可以把它的bug数量降低到万分之一,但市场不会留给公司那么多时间。所以实际上每家公司都是会先开发出一个有基本功能特性的App,然后没2周或者一个月迭代一个版本,通过迭代把这个App完善好。

我们的代码开发大家一定注意,不追求尽善尽美。先让业务能够跑起来,然后我们再进一步追求性能、代码可读性达到90甚至98分的程度。

switch能否作用于Long,string上

switch原则上只能作用于int型上,

但是,char、float、char等可以隐式的转换为int 型,而long,string不可以,

所以呢,switch 不可以作用于Long, string 类型的变量上。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。

上一篇:Java switch支持的数据类型详解
下一篇:没有了
网友评论