java - 增强for循环 - 自动装箱/拆箱 - 可变参数 - 静态导入

来源:互联网 发布:java web页面打印功能 编辑:程序博客网 时间:2024/06/05 04:12

增强for循环

[java] view plain copy
  1. package com.itlwc;  
  2.   
  3. public class Test {  
  4.     public static void main(String[] args) {  
  5.         int[] str = new int[] { 12 };  
  6.         for (int s : str) {  
  7.             System.out.println(s);  
  8.         }  
  9.     }  
  10. }  
  11. /* 
  12. 打印结果: 
  13.     1 
  14.     2 
  15. */  

自动装箱/自动拆箱

[plain] view plain copy
  1. 根据基本类型和包装类来说的,大大方便了基本类型和包装类的使用    
  2. 自动装箱: 基本类型转换为包装类    
  3. 自动拆箱: 包装类转换为基本类型  
案例

[java] view plain copy
  1. package com.itlwc;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5.   
  6. public class Test {    
  7.     public static void main(String[] args) {    
  8.         Collection<Integer> c = new ArrayList<Integer>();    
  9.         c.add(3);// 自动装箱,将int类型的3转换为Integer类型放入集合中    
  10.         c.add(4);    
  11.         for (Integer in : c) {    
  12.             System.out.println(in);// 自动拆箱    
  13.         }    
  14.     }    
  15. }  
  16. /* 
  17. 打印结果: 
  18.     3 
  19.     4 
  20. */  

可变参数

[plain] view plain copy
  1. 可变参数本质就是一个数组,对于某个声明了可变参数的方法来说,可以传入离散的值,  
  2.     也可以传入数组对象,可变参数必须作为方法参数的最后一个,  
  3.     也就是说一个方法参数中不能有两个可变参数   
案例
[java] view plain copy
  1. package com.itlwc;  
  2.   
  3. public class Test {      
  4.     public static void main(String[] args) {      
  5.         int a = sum(12345);      
  6.         System.out.println(a);      
  7.         int b = sum(new int[] { 1234 });      
  8.         System.out.println(b);      
  9.     }      
  10.       
  11.     public static int sum(int... is) {      
  12.         int sum = 0;      
  13.         for (int i : is) {      
  14.             sum += i;      
  15.         }      
  16.         return sum;      
  17.     }      
  18. }  
  19. /* 
  20. 打印结果: 
  21.     15 
  22.     10 
  23. */  

静态导入

[java] view plain copy
  1. package com.itlwc;  
  2.   
  3. import static java.lang.Math.pow;  
  4. import static java.lang.Math.sqrt;  
  5.   
  6. public class Test {  
  7.     public static void main(String[] args) {  
  8.         //未使用静态导入  
  9.         double d1 = Math.pow(32) + Math.sqrt(4);  
  10.         System.out.println(d1);  
  11.         //使用静态导入,看起来简单多了  
  12.         double d2 = pow(32) + sqrt(4);  
  13.         System.out.println(d2);  
  14.   
  15.     }  
  16. }  
0 0