Java 7 的 7 个新的 “酷” 特性

1. switch 中使用字符串变量

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void testStringSwitch(String direction) {  
  2.   switch (direction) {  
  3.      case "up":  
  4.      y--;  
  5.      break;  
  6.      case "down":  
  7.      y++;  
  8.      break;  
  9.      case "left":  
  10.      x--;  
  11.      break;  
  12.      case "right":  
  13.      x++;  
  14.      break;  
  15.     default:  
  16.     System.out.println("Invalid direction!");  
  17.     break;  
  18.   }  
  19. }  

2. 简化泛型对象创建

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Java 7 以前版本  
  2. Map<String,Map<String,int>>m=new HashMap<String, Map<String,int>>();  
  3. // Java 7  
  4. Map<String, Map<String, int>> m = new HashMap<>();  

3. 多异常处理

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. try {  
  2.     Class a = Class.forName("wrongClassName");  
  3.     Object instance = a.newInstance();  
  4. catch (ClassNotFoundException | IllegalAccessException |  
  5.    InstantiationException ex) {  
  6.    System.out.println("Failed to create instance");  
  7. }  

4. 资源的自动释放

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. try (BufferedReader in=new BufferedReader(new FileReader("test.txt")))  
  2. {  
  3.     String line = null;  
  4.     while ((line = in.readLine()) != null) {  
  5.     System.out.println(line);  
  6.     }  
  7. catch (IOException ex) {  
  8.     ex.printStackTrace();  
  9. }  

5. 文件 IO API 的改进

下面是列出一个文件中所有行并打印的方法
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. List<String> lines =  Files.readAllLines(  
  2. FileSystems.getDefault().getPath("test.txt"), StandardCharsets.UTF_8);  
  3.    
  4. for (String line : lines) System.out.println(line);  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值