devxlogo

Java Tip: Optimization Technique for Lists

Java Tip: Optimization Technique for Lists

The default size for a Java ArrayList class is 10. When an ArrayList reaches its capacity maximum (10), it increases its capacity by approximately half. That is why an ArrayList takes more time if it is not initialized with the proper size. When you add objects to an ArrayList and it reaches its maximum capacity, it creates another, bigger array (with a capacity of approximately 15) and copies the previous and new objects into the new array.

Obviously, creating a new array and copying objects is costly to performance. So, the best approach is to initialize the ArrayList with a proper size. To do this, you use constructors or ensureCapacity(int capacity), which results in better performance.

For example, use this code if you expect your ArrayList to store around 3000 objects:

List<String> str = new ArrayList(3000)
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist