Collection vs Collections
Collection (Interface)
- Interface ใน Java Collections Framework
- Root interface สำหรับ List, Set, Queue
- ไม่ได้มีทั้งหมดเป็น static methods
- ใช้เก็บกลุ่ม objects ใน single object
Collections (Utility Class)
- Utility class ใน Collections Framework
- มี เฉพาะ static methods
- ให้ convenience methods: sorting, searching, synchronizing, unmodifiable views, etc.
- Methods ทั้งหมดโยน NullPointerException ถ้า argument เป็น null
ตารางเปรียบเทียบ
| Key | Collection | Collections |
| Basic | Interface ใน Collection Framework | Utility class ใน Collection Framework |
| Static Methods | ไม่ใช่ทั้งหมด | มีเฉพาะ static methods |
| Operation | เก็บ list of objects | ดำเนินการบน collection |
ตัวอย่าง
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Collection (List)
List list = new ArrayList();
list.add("HCL");
list.add("DELL");
// Collections (utility)
Collections.sort(list); // static method
list.forEach(System.out::println);
}
}
สรุป
- Collection = Interface (data structure)
- Collections = Class (algorithms/operations)
- ชื่อคล้ายกันแต่งานคนละอย่าง