I have an ArrayList that I want to convert this is my code :
ArrayList<PostWrapper> postWrapperList = listingWrapper.getData();
int size = postWrapperList.size();
ArrayList<Post> postList = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
PostWrapper postWrapper = postWrapperList.get(i);
if (postWrapper.isKindLink()) {
Post post = postWrapper.getData();
postList.add(post);
}
}
postList.removeAll(Collections.singleton(null));
As you can see in this code I'm doing some kind of filtering so the final size can be smaller than the initial size. Currently I'm calling removeAll() to remove null object to shrink the ArrayList.
My question is which is more efficient, this way or just creating ArrayList without any initial size and then just let the ArrayList class handling the dynamic allocation?
I'm concerned with deallocating excess capacity that I reserved when creating the list.
removeAll()since unused capacity is not considered part of the list. The question is not clear enough to be answered yet.Post. Unless the list size is in the hundreds of thousands, don't worry about it. If you really want to do it you have to copy the list to a new one of the correct capacity. BTW, this smells like premature optimization.trimToSize()if you really, really need to do it and are sure you won't be adding any more elements. But remember it costs time to do the copy. I'd leave things alone until you can show you actually need to trim it.