Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ทำไมต้องใช้ Wrapper Class ใน Java?

Wrapper Class ห่อหุ้ม Primitive Data Types (int, char, short, byte, etc) ให้เป็น Object อยู่ใน package java.lang (ไม่ใช่ java.util)

ทำไมต้องใช้ Wrapper Class?

  • แปลง Primitive → Object จำเป็นตอนส่ง argument ให้เมธอดที่รับ Object (Primitive ส่ง by value)
  • Collections Framework (ArrayList, Vector, HashMap) เก็บได้แค่ Object ไม่เก็บ Primitive โดยตรง
  • Synchronization ใน Multithreading ต้องการ Object สำหรับ lock/monitor
  • Null Value Primitive ไม่สามารถเป็น null ได้ Wrapper ได้ (เช่น Integer = null)
  • Utility Methods พร้อมเมธอดช่วย: parseInt, toString, compareTo, valueOf

Autoboxing (Primitive → Object)

Java 5+ แปลงอัตโนมัติ


public class AutoBoxingTest {
    public static void main(String args[]) {
        int num = 10;
        Integer obj = Integer.valueOf(num); // หรือ Integer obj = num; (autoboxing)
        System.out.println(num + " " + obj); // 10 10
    }
}

Unboxing (Object → Primitive)

Java 5+ แปลงอัตโนมัติ


public class UnboxingTest {
    public static void main(String args[]) {
        Integer obj = new Integer(10);
        int num = obj.intValue(); // หรือ int num = obj; (unboxing)
        System.out.println(num + " " + obj); // 10 10
    }
}

Wrapper Classes ทั้ง 8 ตัว

PrimitiveWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

ข้อควรระวัง

  • Wrapper เป็น Immutable ค่าไม่เปลี่ยนหลังสร้าง
  • Autoboxing/Unboxing มี Overhead เล็กน้อย (สร้าง Object, GC)
  • เปรียบเทียบ Wrapper ใช้ .equals() ไม่ใช่ == (ยกเว้นค่า -128 ถึง 127 ที่ cached)
  • NullPointerException ถ้า Unboxing ค่า null