1. 程式人生 > 實用技巧 >java7新特性簡單介紹

java7新特性簡單介紹

switch對字串的支援

public class Client {
  public static void main(String[] args) {
    String name = "lisi";
    switch (name) {
      case "lisi":
        System.out.println(name);
        break;
      case "wangwu":
        System.out.println(name);
        break;
      case "zhangsan":
        System.out.println(name);
        break;
    }
  }
}

其實java編譯器會幫我們轉換成字串的hashcode()

數字字面量改進

public class Client {
  public static void main(String[] args) {
//二進位制支援
    int num1 = 0B1001;
    System.out.println(num1);
//支援加_
    num1 = 1_000_000;
    System.out.println(num1);
  }
}

編譯器幫我們轉成10進位制,去掉_

try-with-resources語句

在try語句中申請資源,實現資源的自動釋放,資源需要實現AutoCloseable介面,檔案、資料庫連線等都已實現。

public class Client {
  public static void main(String[] args) {
    try (ByteArrayInputStream bais = new ByteArrayInputStream("hello".getBytes());
         ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
      int len = -1;
      while ((len = bais.read()) != -1) {
        baos.write(len);
      }
      System.out.println(new String(baos.toByteArray()));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

編譯器會自動呼叫資源的close方法。

增強泛型推斷

public class Client {
  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
  }
}

編譯期會自動推斷HashMap的型別

NIO2(AIO)的支援

public class Client {
  public static void main(String[] args) throws IOException {
    AsynchronousFileChannel fileChannel = AsynchronousFileChannel
        .open(Paths.get("D:\\Client.java"));
    fileChannel.read(ByteBuffer.allocate(4098), 0, "hello", new CompletionHandler<Integer, String>() {
      @Override
      public void completed(Integer result, String attachment) {
        System.out.println(result);
        System.out.println(attachment);
      }

      @Override
      public void failed(Throwable exc, String attachment) {
        System.out.println(exc);
        System.out.println(attachment);
      }
    });
  }
}

非同步檔案通道,在檔案讀取完成執行回撥方法