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

ความแตกต่างระหว่าง ArrayList และ Vector ใน Java

ArrayList

  • Non-synchronized (Not thread-safe)
  • ขยายขนาด 50% เมื่อเต็ม
  • เพิ่มใน JDK 1.2
  • ใช้ Iterator เท่านั้น
  • เร็วกว่า (เพราะไม่ synchronized)

Vector

  • Synchronized (Thread-safe)
  • Legacy class (มาตั้งแต่ JDK 1.0)
  • ขยายขนาด 100% (double) เมื่อเต็ม
  • ใช้ได้ทั้ง Enumeration และ Iterator
  • ช้ากว่า (เพราะ synchronized)
  • ให้สภาพแวดล้อม Multi-threading

ตัวอย่าง宣告

ArrayList al = new ArrayList();
Vector v = new Vector();

สรุป: ควรใช้ตัวไหน?

  • Single-thread หรือจัดการ sync เอง → ArrayList (เร็วกว่า)
  • Multi-thread ต้องการ built-in sync → Vector (แต่แนะนำ Collections.synchronizedList หรือ Concurrent collections แทน)