Java JDK5.0的新特性 增强for循环 自动装箱/拆箱 可变参数 静态导入

来源:互联网 发布:ios电影下载软件 编辑:程序博客网 时间:2024/05/16 07:06

Java JDK5.0的新特性 增强for循环 自动装箱/拆箱 可变参数 静态导入

分类: JavaSE 71人阅读 评论(0) 收藏 举报

增强for循环

[java] view plaincopy
  1. public class Test {  
  2.     public static void main(String[] args) {  
  3.         int[] str = new int[] { 123456 };  
  4.         for (int s : str) {  
  5.             System.out.println(s);  
  6.         }  
  7.     }  
  8. }  
自动装箱/自动拆箱

[java] view plaincopy
  1. 是根据基本类型和包装类来说的,大大方便了基本类型和包装类的使用    
  2. 自动装箱    
  3.     基本类型转换为包装类    
  4. 自动拆箱        
  5.     包装类转换为基本类型  
  6. import java.util.ArrayList;    
  7. import java.util.Collection;    
  8. /******自动装箱和自动拆箱******/    
  9. public class Test {    
  10.     public static void main(String[] args) {    
  11.         Collection<Integer> c = new ArrayList<Integer>();    
  12.         c.add(3);// 自动装箱,将int类型的3转换为Integer类型放入集合中    
  13.         c.add(4);    
  14.         for (Integer in : c) {    
  15.             System.out.println(in);// 自动拆箱    
  16.         }    
  17.     }    
  18. }  

可变参数

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

静态导入

[java] view plaincopy
  1. package com.itlwc;  
  2. /**************不使用静态的导入*************/  
  3. public class Comnon {  
  4.     public static void main(String[] args) {  
  5.         double d = Math.pow(32) + Math.sqrt(4);  
  6.         System.out.println(d);  
  7.     }  
  8. }  
  9.   
  10. package com.itlwc;  
  11. import static java.lang.Math.pow;  
  12. import static java.lang.Math.sqrt;  
  13. /**************不使用静态的导入*************/  
  14. public class Comnon {  
  15.     public static void main(String[] args) {  
  16.         //这块看起来就简洁多了  
  17.         double d = pow(32) + sqrt(4);  
  18.         System.out.println(d);  
  19.     }  
  20. }  

原创粉丝点击