java中有哪些语法糖,泛型的原理

xiaoxiao2021-02-28  27

java中的语法糖:型、自动装箱拆箱、变长参数、增强for循环、switch字符类型等,这些都是语法糖 虚拟机运行时不支持这种语法,在编译期间这些内容会被还原为基础的语法结构,这个过程称为解语法糖 我们拿泛型来说明:它只在程序源码中存在,在编译后的字节码文件中,就已经替换为原来的原生类型(也称为裸类型)了,并且在相应的地方插入了强制转型代码,因此,对于运行期的Java语言来说,ArrayList<int>与ArrayList<String>就是同一个类,所以泛型技术实际上是Java语言的一颗语法糖,Java语言中的泛型实现方法称为类型擦除,基于这种方法实现的泛型称为伪泛型 最后,我们看两个实际例子 public static void main(String[]args){ Map<String,String>map=new HashMap<String,String>(); map.put("hello","你好"); map.put("how are you?","吃了没?"); System.out.println(map.get("hello")); System.out.println(map.get("how are you?")); }//-----这一段是泛型代码, public static void main(String[]args){ Map map=new HashMap(); map.put("hello","你好"); map.put("how are you?","吃了没?"); System.out.println((String)map.get("hello")); System.out.println((String)map.get("how are you?")); }//-----这一段是泛型擦除后的代码 --------------------------------------------------------------------再看下面一个例子 public static void main(String[]args){ List<Integer>list=Arrays.asList(1,2,3,4);//这一句涉及自动装箱以及变长参数语法糖 int sum=0; for(int i:list){//这一段涉及foreach增强遍历器以及自动拆箱语法糖 sum+=i; } System.out.println(sum); } //上面代码编译后如下 public static void main(String[]args){ List list=Arrays.asList(new Integer[]{//变长参数被转为数组, Integer.valueOf(1),//int类型被装箱为Integer Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4)}); int sum=0; for(Iterator localIterator=list.iterator();localIterator.hasNext();){ int i=((Integer)localIterator.next()).intValue();//Integer拆箱为int sum+=i; }//foreach循环被编译为通过迭代器遍历 System.out.println(sum); } 这些语法糖虽然不会提供实质性的功能改进,但是它们或能提高效率,或能提升语法的严谨性,或能减少编码出错的机会,方便了程序员的代码开发
转载请注明原文地址: https://www.6miu.com/read-2626996.html

最新回复(0)