Popcorn Popcorn - 1 year ago 79
Java Question

are arrays faster than arraylist?

My intuition says arrays are faster than arraylist because arraylists are implemented using arrays that resize as it fills up/loses elements.

I just wanted to confirm if this is true or not, implying there's never a reason to use an arraylist if you know the number of elements you want to hold.

Answer Source

Any performance difference will be negligible, especially if you initialize your arraylist with an initialCapacity. Write your code in whatever way makes it the most readable and maintainable, and try not to optimize stuff like this unless you've determined through testing that you are getting a significant performance hit from it.

Potential reasons to use ArrayList:

  • useful methods (contains, etc.)
  • implements Iterable, Collection, and List, and can therefore be used in a lot of API calls that are interface-based.
  • even though you currently "know" that your collection's size can never change, life throws unexpected requirements at us. Why lock yourself into a pattern when there's no discernible advantage to be gained?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download