Using small (1-10 items) collections of instances in Java

When creating classes in Java, I often find myself creating collections at the instance level that I know in advance will be very small - less than 10 items in the collection. But I do not know the number of elements ahead of time, so I usually choose a dynamic collection (ArrayList, Vector, etc.).

class Foo { ArrayList<Bar> bars = new ArrayList<Bar>(10); } 

Part of me tugging at me wasting the use of complex dynamic collections for something so small. Is there a better way to implement something like this? Or is this the norm?

Note that I am not struck by any (noticeable) penalties for performance or something like that. It only interests me if there is a better way to do something.

+6
java collections
source share
4 answers

The Java ArrayList class has only two data members, a reference to the Object[] array and the size you need if you are not using an ArrayList . Therefore, the only advantage of not using ArrayList is the preservation of a single distribution of objects, which is unlikely to ever be of great importance.

If you create and delete many, many instances of your container class (and, in turn, your ArrayList instance) every second, you may have a little garbage collection problem, but something to worry about is this ever happening. Garbage collection is usually the least of your worries.

+11
source share

For the convenience of things, I believe that this is not a problem. Your implementation is flexible enough so that if you change requirements in the future, you are not refactored. In addition, adding extra logic to your code for a hybrid solution is simply not worth considering your small dataset and high-quality Java Collection APIs.

+3
source share

Google Collections contains collections optimized for an immutable / small number of items. See the Lists.asList API for an Lists.asList .

+2
source share

Overhead is very small. You can write a list of hybrid arrays that has fields for the first few elements, and then returns to using an array for a longer list.

You can completely avoid the overhead of a list object by using an array. To make it even more hardcore, you can declare this field as Object and completely exclude the array for one element.

If memory is really a problem, you can forget about using instances of objects at the low level. Instead, use a larger data structure at a higher level of detail.

+1
source share

All Articles