Comparisons

Java 常見類別與概念的差異比較表。

ArrayList vs Vector

FeatureArrayListVector
Thread-SafetyNot synchronized by defaultSynchronized by default
PerformanceMore efficient, better for single-threaded applicationsSlower due to synchronization, better for multi-threaded applications
Growth RateIncreases 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
LegacyPart of the Java Collections Framework, recommended choice for general-purpose scenariosPart of the original Java Collection classes, considered a legacy class

Comparable vs Comparator

AspectComparable (I)Comparator (I)
PurposeAllows objects to define their natural orderingProvides a separate class to define custom sorting order
Interface Methodint compareTo(T o)int compare(T o1, T o2)
Sorting OrderObjects are sorted in their natural orderCustom sorting order can be defined
SortingsObjects can have only one natural sorting orderMultiple comparators can be defined for different sorting orders
ImplementationImplemented by the class of the objects being comparedImplemented by a separate class
UsageImplicitly used by sorting methods (e.g., Collections.sort())Explicitly passed to sorting methods
Multiple SortingTo change sorting order, modify the object’s compareTo() methodTo change sorting order, create and use different comparators
ExampleSorting a list of strings in lexicographic orderSorting a list of custom objects based on specific attributes
affects the original classdoesn’t affect the original class
可比較的比較器
  • Comparable

    • Use Case : 當你想要默認排序一個類的實例時,比如字典順序、數字大小等,並且排序邏輯在大多數情況下不會改變。
  • Comparator

    • Use Case : 當你想要根據不同的屬性或條件進行排序,或者不希望修改類的 compareTo 方法時。

Callable vs Runnable

FeaturesCallableRunnable
Return valueCan return valueNo return value
Exception handlingCan throw checked exceptionsCannot throw checked exceptions
Method signatureV call() throws Exceptionvoid run()
Used inFutureThread

StringBuffer vs StringBuilder

KeyStringBufferStringBuilder
版本Java 1Java 5
同步YesNo
效能Thread-Safe, SlowNot Thread-Safe, Faster than StringBuffer
儲存位置HeapHeap
  • StringBuffer :
    • 沒有 override equals,Object equals 為 == 比較記憶體位址
    • StringBuffer 字串 與 String 字串 比較無意義,Object equals 前提是同類型物件

Lock vs Synchronized

  1. Synchronized blocks must be contained within a single method. lock.lock() and lock.unlock() can be called from different methods.
  2. lock.lock() and lock.unlock() provides the same visibility and happens before guarantees as entering and exiting a synchronized block
  3. Synchronized blocks are always reentrant. Lock could decide not to be.
  4. Synchronized blocks do not guarantee fairness. Locks can.
LockSynchronized
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

ArrayLinked 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

OperationsSINGLETONLISTLIST::OFARRAYS::ASLISTJAVA.UTIL.ARRAYLIST
add✔️
addAll✔️
clear✔️
remove✔️
removeAll❗️❗️✔️
retainAll❗️❗️✔️
replaceAll✔️✔️
set✔️✔️
sort✔️✔️✔️
remove on iterator✔️
set on list-iterator✔️✔️