การเปลี่ยนแปลงจนถึง Java8

เป็นการสรุปที่อบรมมาค่ะ เอาแบบสั้นมากๆ

Java5

  • Fast Loop
for (int x : list)
  • Variable Argument 
public void doSomething (int... listInt)
  • Format (printf)
  • Enumeration ที่เป็น type safe
  • Autoboxing
  • Generic type
  • Annotation
  • Document annotation
  • Static import package
import static java.lang.math.*;

Java6

  • Script engine สามารถ run javascript ใน java ได้ ผ่าน class javax.script.ScriptEngine
  • String pool คือมีการรวมค่าของ string ที่เป็นค่าเดียวกันไว้ด้วยกัน (แต่ไม่ใช่ค่า string ตอน runtime)
String s1 = "Hello";
String s2 = "Hello"; // s1 = s2

String s3 = new String("Hello"); // s1 <> s3
String s4 = s3.intern(); // s1 == s4

Java7

  • String switcher คือใช้ string ในการเลือก case ได้
  • Literal underscore สามารถเพิ่ม _ เพื่อให้อ่านง่าย
long a = 127_777;
byte x = 0b0111_1111;
  • DiamondOp คือสามารถละ type ที่กำหนดใน generic class ได้
List b = new ArrayList<>();
  • Null safe มี java.util.Objects ที่เป็น utility สำหรับจัดการค่าที่สามารถเป็น null ได้ เช่น equals(), toString()
  • Multi-catch
try {
...
} catch (IndexOutOfBoundsException | NumberFormatException | ArithmeticException ex) {
    System.out.println(ex.getClass());
}

  • Try resource block
try (
/* create auto-closeable resource object (class that implements AutoCloseable interface) */
) {
...
} catch (Exception ex) {
...
}
  • Walk โดยการเพิ่ม FileVisitor ใช้กับ Files.walkFileTree
  • Watch โดยมี WatchService 
WatchService ws = FileSystems.getDefault().newWatchService();
Path p = Paths.get("temp");
p.register(ws, StandardWatchEventKinds.ENTRY_DELETE);

Java8

  • Interface สามารถสร้าง static method โดยจะต้องเป็น concrete method และเรียกผ่าน Interface ไม่ใช่เรียกที่ class
  • Interface สามารถสร้าง default method ที่เป็น concrete method ได้
  • Lambda ซึ่งจะถูกสร้างเป็น private method ใน class นั้นๆ (แม้ว่าจะคล้าย anonymous class) โดยใช้ annotation @FunctionalInterface เพื่อให้ compiler เช็คว่า interface เป็น SAM (Single Abstract Method) หรือเปล่า หรือจะใช้ predefined functional type (java.util.function.*) ก็ได้
  • Optional ซึ่งเป็น class ใหม่ เพื่อไม่ให้เกิด NullPointerException แต่ต้องใช้คู่กับ method orElse, orElseGet, orElseThrow หรือ ifPresent (ทั้งนี้จะใช้ Optional ก็จะต้องรู้เรื่อง Lambda ก่อน เพราะว่าหลาย method จะต้องใช้ความสามารถนี้)
  • Stream เป็น class ใหม่ และเพิ่ม method steam() ใน Collection และ Arrays เพื่อใช้ในการสร้าง stream หรือใช้ method of ของ Stream และเพิ่มค่าใน Stream โดย method add
Stream ss = Arrays.stream(array);

Stream sa = Stream.of(array);

Stream sd = Stream.generate(Math::random).limit(3); // สร้างค่าสุ่ม 3 ค่า

Stream sf = Files.lines(Paths.get("test.txt")); // สามารถอ่านจาก IO Stream ได้ด้วย

  • Parallel โดยสามารถใช้ได้บน Stream โดยแค่กำหนดเป็น Stream.parallel()
  • Parallel โดยใช้ class CompletableFuture

No comments:

Post a Comment