Comparisons
Java 常見類別與概念的差異比較表。
ArrayList vs Vector
| Feature | ArrayList | Vector |
|---|---|---|
| Thread-Safety | Not synchronized by default | Synchronized by default |
| Performance | More efficient, better for single-threaded applications | Slower due to synchronization, better for multi-threaded applications |
| Growth Rate | Increases size by a certain factor when needed (usually 50% or doubles) | Increases size by a certain factor when needed (usually doubles), growth rate can be specified |
| Legacy | Part of the Java Collections Framework, recommended choice for general-purpose scenarios | Part of the original Java Collection classes, considered a legacy class |
Comparable vs Comparator
| Aspect | Comparable (I) | Comparator (I) |
|---|---|---|
| Purpose | Allows objects to define their natural ordering | Provides a separate class to define custom sorting order |
| Interface Method | int compareTo(T o) | int compare(T o1, T o2) |
| Sorting Order | Objects are sorted in their natural order | Custom sorting order can be defined |
| Sortings | Objects can have only one natural sorting order | Multiple comparators can be defined for different sorting orders |
| Implementation | Implemented by the class of the objects being compared | Implemented by a separate class |
| Usage | Implicitly used by sorting methods (e.g., Collections.sort()) | Explicitly passed to sorting methods |
| Multiple Sorting | To change sorting order, modify the object’s compareTo() method | To change sorting order, create and use different comparators |
| Example | Sorting a list of strings in lexicographic order | Sorting a list of custom objects based on specific attributes |
| affects the original class | doesn’t affect the original class | |
| 可比較的 | 比較器 |
Comparable
- Use Case : 當你想要默認排序一個類的實例時,比如字典順序、數字大小等,並且排序邏輯在大多數情況下不會改變。
Comparator
- Use Case : 當你想要根據不同的屬性或條件進行排序,或者不希望修改類的
compareTo方法時。
- Use Case : 當你想要根據不同的屬性或條件進行排序,或者不希望修改類的
Callable vs Runnable
| Features | Callable | Runnable |
|---|---|---|
| Return value | Can return value | No return value |
| Exception handling | Can throw checked exceptions | Cannot throw checked exceptions |
| Method signature | V call() throws Exception | void run() |
| Used in | Future | Thread |
StringBuffer vs StringBuilder
| Key | StringBuffer | StringBuilder |
|---|---|---|
| 版本 | Java 1 | Java 5 |
| 同步 | Yes | No |
| 效能 | Thread-Safe, Slow | Not Thread-Safe, Faster than StringBuffer |
| 儲存位置 | Heap | Heap |
StringBuffer:- 沒有
override equals,Object equals 為 == 比較記憶體位址 StringBuffer字串 與 String 字串 比較無意義,Object equals 前提是同類型物件
- 沒有
Lock vs Synchronized
- Synchronized blocks must be contained within a single method.
lock.lock()andlock.unlock()can be called from different methods. lock.lock()andlock.unlock()provides the same visibility and happens before guarantees as entering and exiting a synchronized block- Synchronized blocks are always reentrant. Lock could decide not to be.
- Synchronized blocks do not guarantee fairness. Locks can.
Lock | Synchronized | |
|---|---|---|
| Across Method | ⭕ | ❌ |
| try to acquire lock | ⭕ | ❌ |
| Fair lock management | ⭕ | ❌ |
| List of waiting threads | ⭕ | ❌ |
Release of lock in exceptions
- Lock
// Situation 1
lock.lock();
doSomethingNifty(); // Throws exception
lock.unlock(); // Oh no, we never release the lock!
// Situation 2
try {
lock.lock();
} finally {
lock.unlock(); // need write unlock() in finally
}- Synchronized
When an exception occurs from within a synchronized code block, then JVM smartly releases all the locks acquired by the current thread and will start unwinding the execution stack, till the exception is handled using catch block, otherwise killing the thread.
LinkedList vs Array
| Array | Linked List | |
|---|---|---|
| 儲存結構 | 儲存相同類型的資料 | 儲存的Object裡面都包含Data與Pointer(指向下一個Node) |
| 記憶體儲存位置 | elements 會存在 sequential memory locations(有順序的記憶體位置) | elements 隨機儲存在記憶體當中某個位置, element指向下一個 element(sequence of the elements) |
| 記憶體空間 | 需要宣告空間 | 不受限 |
| 存取方式 | 利用index搜索 | 必須從頭尋找資料 |
| 優點 | Search O(1),較快搜索資料 | 新增、刪除資料較Array簡單,只要O(1) |
| 較節省記憶體空間 | ||
| 缺點 | 新增、刪除資料需要移動整個Array, 花費 O(N)時間在移動舊陣列到新陣列 | Search O(N), 沒有index,需要從頭搜尋起 |
| 需要另外記憶體空間儲存 pointer |
List.of vs Arrays.asList
| Operations | SINGLETONLIST | LIST::OF | ARRAYS::ASLIST | JAVA.UTIL.ARRAYLIST |
|---|---|---|---|---|
| add | ❌ | ❌ | ❌ | ✔️ |
| addAll | ❌ | ❌ | ❌ | ✔️ |
| clear | ❌ | ❌ | ❌ | ✔️ |
| remove | ❌ | ❌ | ❌ | ✔️ |
| removeAll | ❗️ | ❌ | ❗️ | ✔️ |
| retainAll | ❗️ | ❌ | ❗️ | ✔️ |
| replaceAll | ❌ | ❌ | ✔️ | ✔️ |
| set | ❌ | ❌ | ✔️ | ✔️ |
| sort | ✔️ | ❌ | ✔️ | ✔️ |
| remove on iterator | ❌ | ❌ | ❌ | ✔️ |
| set on list-iterator | ❌ | ❌ | ✔️ | ✔️ |