Object Arrays คืออะไร?
Array ที่เก็บ Reference ของ Object (ไม่ใช่ Primitive) สร้างได้เหมือน Array ปกติ
ตัวอย่าง
class Std {
static int year = 2018;
String name; int age;
Std(String name, int age) { this.name = name; this.age = age; }
void display() {
System.out.println("Name: " + name + ", Age: " + age + ", Year: " + year);
}
}
public class Sample {
public static void main(String args[]) {
Std[] st = new Std[4]; // Array ของ Std references
st[0] = new Std("Bala", 18);
st[1] = new Std("Rama", 17);
st[2] = new Std("Raju", 15);
st[3] = new Std("Raghav", 20);
for (Std s : st) s.display();
}
}
ผลลัพธ์
Name: Bala, Age: 18, Year: 2018 Name: Rama, Age: 17, Year: 2018 Name: Raju, Age: 15, Year: 2018 Name: Raghav, Age: 20, Year: 2018
ข้อเสียของ Object Arrays
- Fixed Size: ต้องรู้ขนาดล่วงหน้า ไม่สามารถ resize ได้
- No Built-in Methods: ไม่มี add/remove/search/sort ต้องเขียนเองหรือใช้ Arrays utility
- Memory Overhead: เก็บ References + Object Header แต่ละตัว (มากกว่า Primitive Array หรือ Collections)
- Type Safety: Compile-time ตรวจสอบได้แค่ Base Type (เช่น Std[]) ใส่ Subclass ได้ แต่ Runtime อาจผิด
- Null Elements: อาจมี null ระหว่างกลาง ต้องเช็ค NullPointerException
แนะนำ: ใช้ Collections (ArrayList, List) แทน
- Dynamic Size
- Rich API (add, remove, contains, stream, sort, ...)
- Generics Type Safety
- Memory Efficient (สำหรับ Primitive ใช้ Specialized Collections หรือ Arrays)