Using small (1-10 items) instance level collections in Java

When creating classes in Java, I often find that the instance level collection I create is very small - there are less than 10 items in the collection But I don't know the number of items in advance, so I usually choose dynamic sets (ArrayList, vector, etc.)

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

Part of me has been nagging me that using complex dynamic sets to deal with such small things is wasteful Is there a better way to do this? Or is this normal?

Please note that I haven't experienced any (obvious) performance loss or anything like that It's just that I want to know if there is a better way to do things

Solution

The ArrayList class in Java has only two data members, a reference to the object [] array and a size - if you don't use ArrayList, you need it Therefore, the only benefit of not using ArrayList is to save an object assignment, which is unlikely to be a big problem

If you are creating and processing many instances of container classes (and extending your ArrayList instances) every second, there may be some problems with garbage collection loss - but worry if it happens Garbage collection is usually the least of your worries

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>