Autobox Unbox ในภาษา Java
Boxing คือการแปลงของค่า primitive ไปเป็นค่าของ wrapper instance เช่น แปลงค่าจาก int ไปเป็น IntegerUnboxing คือการแปลงค่าจาก wrapper instance ไปเป็นค่าของ primitive เช่น แปลงค่าจาก Integer ไปเป็น int
มาดูตัวอย่างโค้ดกันเลยครับ
package info.doesystem.howto;
public class DoesystemInfo {
public static void main(String[] args) {
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb);
}
}
จากตัวอย่างโค้ดจะเห็นว่า Integer iOb = 100 จะเป็นการ autobox ซึ่งจะเป็นการแปลงค่าจาก int ไปเป็น Integer และจะเห็นว่า int i = iOb จะเป็นการ auto-unbox ซึ่งจะเป็นการแปลงค่าจาก Integer ไปเป็น int
การทำงานของ Autobox กับ Auto-Unbox
เรามาดูการทำงานของ Autobox กับ Auto-Unbox กันครับ ว่ามันทำงานยังไง มันใช้วิธีไหนในการแปลงค่า ซึ่งวิธีการดูนั้น เราจะดูจากไฟล์ .class ที่ได้ compile มาแล้ว เราจะใช้โปรแกรม Java Decompiler ในการดู ซึ่งผลลัพธ์ก็ออกมาดังนี้จากรูปจะเห็นว่าในการ autobox นั้นจะทำการไปเรียก Integer.valueOf() และในการ auto-unbox นั้นจะไปเรียก iOb.intValue() ให้อัตโนมัติ
ข้อควรระวัง
จะเห็นว่าในการ auto-unbox นั้นจะมีการไปเรียก intValue() ซึ่งตรงนี้ถ้า iOb มีค่าเป็น null ละก็จะเกิด NullPointerException ขึ้นมาได้ ดังตัวอย่างโค้ด
package info.doesystem.howto;
public class DoesystemInfo {
public static void main(String[] args) {
Integer iOb = null;
int i = iOb; // auto-unbox
}
}
จากโค้ดจะเกิด Exception in thread "main" java.lang.NullPointerException ขึ้นมา เพราะว่ามีการ auto-unbox กับ Object ที่เป็น null ซึ่งจะไปเรียก intValue() ดังนั้นควรระวังไว้ให้ดี
ไม่มีความคิดเห็น:
แสดงความคิดเห็น