Java 新功能

Posted by Bruce Tsai

Java 5

  • 自動裝箱/拆箱 (Auto-Boxing/Unboxing)
int number = new Integer(10);
Integer value = 10;
  • 泛型 (Generic Types)
List<String> list = new ArrayList<String>();
  • 註釋 (Annotation)
@Description
public String getTypeName(){
   ...
}
  • 列舉類型 (enum)
public enum Gender {
    Male, Female
}
  • 輸入輸出 (Scanner / Formatter)
String str = String.format("Hi %s", name);
  • foreach 迴圈
// 4 以前
for (int i = 0; i < list.size(); i++) {
    // do something
}
// 5
for (Object value : list) {
    // do somthing
}
  • 可變長度的引數
String call(String name, int... values) {
    // do something
}
  • static 引入
import static java.lang.Math.*;

double r = cos(PI * theta);

Java 6

Java 7

  • Diamond Operator
// 6 以前
List<String> list = new ArrayList<String>();
// 7 
List<String> list = new ArrayList<>();
  • switch 字串支援
String value = getValue();
switch (value) {
    case "10":
        // do something
        break;
    case "20":
        // do something
        break;
}
  • Multi-catch
// 6 以前
try {
    execute();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (InterruptedIOException e) {
    e.printStackTrace();
}
// 7
try {
    execute();
} catch (FileNotFoundException | InterruptedIOException e) {
    e.printStackTrace();
}
  • try-with-resource 語法/java.lang.AutoCloseable/自動資源管理(ARM)
// 定義
public class Lock implements AutoCloseable {
    public void close() throws Exception {
        // close lock
    }
}
// 使用
try (Lock lock = new Lock()) {
    // do something
} catch (Exception e) {
    e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(file);
     BufferedInputStream bis = new BufferedInputStream(fis)) {
    // do something
} catch (Exception e) {
    e.printStackTrace();
}
  • 支援二進制數值/數值分割(Enhanced syntax for numeric literals)
int value = 0b1010100;
long anotherLong = 2_147_483_648L;
  • New file system API (NIO 2.0)
Path path= Paths.get("c:\Temp\temp");

Java 8

  • Lambda Expressions
Runnable r = () -> {
    // do something
};

相似功能參考 Retrolambda

  • Method Reference
List<String> names = getNames();
names.forEach(System.out::println);
  • Streams
List<String> strings =
    Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream()
                .filter(string -> !string.isEmpty())
                .collect(Collectors.toList());

相似功能參考 GuavaApach Commons Functor

  • New Date / Time APIs
LocalDateTime currentTime = LocalDateTime.now();

相似功能參考 Joda-Time

  • Default Methods
public interface vehicle {
   default void print(){
      System.out.println("I am a vehicle!");
   }
}

results matching ""

    No results matching ""