TLongArrayList 相较于 long[] 的优势有哪些?
Great question! I’ve used both primitive long[] arrays and TLongArrayList (from Eclipse Collections) in plenty of projects, so let’s walk through why you’d pick the latter in most scenarios:
Dynamic resizing without the hassle
Along[]is fixed-size by nature—if you need to add more elements than you initially allocated, you have to manually create a new array, copy over existing elements withSystem.arraycopy(), and update your reference.TLongArrayListhandles this automatically: it grows its internal array as needed when you calladd()oraddAll(), saving you from writing repetitive error-prone boilerplate.Built-in utility methods to skip manual coding
Need to check if a value exists? Remove an element at a specific index? Sort or reverse the list? Withlong[], you’d either write your own loops or rely onArraysclass methods (which still require extra work).TLongArrayListcomes with all these features out of the box: just callcontains(long),remove(int),sort(), orreverse()directly. It even has methods for filtering, mapping, and aggregating values—no need to reinvent the wheel.No boxing/unboxing overhead (unlike
ArrayList<Long>)
If you tried using a genericArrayList<Long>instead oflong[], you’d pay the cost of boxinglongprimitives intoLongobjects and unboxing them back.TLongArrayListstores rawlongvalues directly (just like an array) but gives you collection-style convenience, so you get the best of both worlds: primitive performance with collection flexibility.Seamless integration with collection frameworks
TLongArrayListimplements theTLongListinterface, which fits into the Eclipse Collections ecosystem. This means you can use it with other library utilities for bulk operations, lazy iteration, or converting between collection types. With a plainlong[], you’d have to manually convert it to a boxedLong[]or wrap it to work with most collection APIs—adding unnecessary steps and overhead.Fine-grained control over memory (when you need it)
While it handles resizing automatically, you still get control: useensureCapacity(int)to pre-allocate space if you know how many elements you’ll add (avoiding multiple small resizes), ortrimToSize()to shrink the internal array to match the actual number of elements and free up unused memory. Withlong[], you’d have to do this manually by creating a new array of the exact size.
Of course, if you’re working with a strictly fixed-size dataset and need absolute minimal overhead, a long[] might still be the right call. But for most real-world use cases where you need flexibility, readability, and less boilerplate, TLongArrayList is a far more practical choice.
内容的提问来源于stack exchange,提问作者CrazySynthax

