ArrayList capacity in Java
1 tuần trướcThe ArrayList ensureCapacity[] method increases the capacity of the given ArrayList instance, if necessary, to ensure that it can hold at least the number of items specified by the method argument minCapacity.
We need to use ensureCapacity[] method in cases when there is a huge number of add[] operations in the ArrayList. In such cases, ArrayList will be frequently resized which is an expensive operation.
1. Syntax
public void ensureCapacity[int minCapacity]If the value of minCapacity is less than 10 which is the default capacity of ArrayList, then the capacity ensured will be 10.
2. Why ArrayList Resizing is Expensive?
Java ArrayList internally uses a backing array object elementData which is used to store the list items. All ArrayList methods operate on this elementData and items stored in it.
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable { private static final int DEFAULT_CAPACITY = 10; transient Object[] elementData; //more code... }This is the reason why ArrayList is an ordered collection and provides index-based access to items.
Note that Arrays are fixed-size collections whereas ArrayList grows in runtime as soon as the backing array elementData is full and more elements are added to the list.
Increasing the size of elementData array is called resizing. This resizing is done in two steps:
- Create a new backing array with more size than previous array.
- Copy all elements from old array to this new array.
So basically, before adding any new item to the ArrayList with add[] method, ArrayList performs a check whether there is any space left in the backing array using ensureCapacity[] method.
If there is any space available in the backing array then the new element is added into the array; else a new backing array is created first.
Read More: ArrayList Sourcecode
3. ArrayList ensureCapacity[] Example
Java program to use ensureCapacity[] method to increase the size of an ArrayList after its initialization.
In given example, we have first created an ArrayList with size 2. Lets suppose we want to add 20 more elements to it, then during the addition resizing will happen a few times.
First-time resizing will grow the list size to 10. Then subsequent add[] operations will cause the array to resize a few more times.
To avoid this resizing many times, we can call ensureCapacity[] method with a size of 25. This will make enough room in the array to store all the additional 20 items that we are going to add. It improves the overall performance of the whole program.
public class ArrayListExample { public static void main[String[] args] { ArrayList list = new ArrayList[2]; list.add["A"]; list.add["B"]; System.out.println[list]; list.ensureCapacity[25]; list.add["C"]; list.add["D"]; list.add["E"]; System.out.println[list]; } }Program output.
[A, B] [A, B, C, D, E]Happy Learning !!
Read More:
A Guide to Java ArrayList
ArrayList Java Docs
Was this post helpful?
Video liên quan
Bài Viết Liên Quan
Câuwishhay còn gọi là câu điều ước [tiếng Anh là wish sentences] là điểm ngữ pháp cơ bản và quan trọng. Bên cạnh các thì, câu điều kiện, câu bị động và ...
Combo BoxesLast Updated on Wed, 06 Jan 2021 | Access 2007 VBAThe combo box is a potent control that can combine the processes to search, select, and populate data into fields [or other objects], as ...
Official Singles Chart Top 10017 December 2021 - 23 December 2021The Official UK Top 40 chart is compiled by the Official Charts Company, based on official sales of sales of downloads, CD, vinyl, ...
FAFabian1 reviewCA8 hours agostuck withdrawalstuck withdrawal, no support, over 23k in. globalrecovery.link intervened just in timeCJCrypto Jouda1 reviewCZ2 days agoStay away from this exchangeThey ...
Posted: 09/30/2017OptionsPermalinkHistorySubscribeUnsubscribePower button jammed after dropping it,I. n no longer press's the button after it fell of my bed. The screen and everything else is ...
Most Streamed Spotify Songs for 66 Rock + Metal ActsChad ChildersPublished: August 14, 2020Matt Stasi, Loudwire / Mark Horton / Ethan Miller, Getty ImagesSHARETWEETWhat is a band's biggest song? For ...
lis·ten | \ ˈli-sᵊn \listened; listening\ ˈlis-niŋ , ˈli-sᵊn-iŋ \1 : to pay attention to someone or something in order to hear what is being said, sung, played, etc. I listened ...
Ulasan Lengkap 5 Laptop Asus 4 Jutaan Terbaik dan Terlaris 2021Jika melihat mahasiswa masa kini, laptop sudah jadi kebutuhan paling urgent untuk kegiatan belajar di kampus. Mau jurusan kuliah apapun, ...
ListingPro Multipurpose Directory ThemeThe ListingPro theme is a flexible and highly customizable directory theme that you can use to create online directory of any niche.You can use this theme to ...
Holistic medicine involves the use of alternative therapies such as massage or acupuncture paired with traditional health care. One-third of American adults are adding holistic medicine into their ...
Life Lessons We Can Learn from Blacklist's Raymond Reddington ...
Hp 17.3 inch Core i5 7th Gen 8GB RAM Price in Philippines is PHP 20,910 as of December 23, 2021The Latest Hp 17.3 inch Core i5 7th Gen 8GB RAM Price in Philippines updated on daily bases from the ...
List Box exampleLast Updated on Thu, 08 Apr 2021 | Excel VBA ProgrammingListBoxes are useful controls, but working with them can be a bit tricky. Before displaying a dialog box that uses a ListBox, ...
Điều đầu tiên mà tôi muốn nhấn mạnh với các bạn để không phải lo lắng, buồn phiền gì cả là: pin có sạc thế nào hay dùng thế nào cũng đều bị chai ...
Hệ điều hành Windows hỗ trợ các tổ hợp phím trong máy tính mang lại cho người dùng sự tiện lợi cao khi sử dụng. Các bạn chỉ cần nhớ các phím tắt trên ...
Top 11 trung tâm sửa chữa máy tính/laptop uy tín nhất tại TPHCM 27-04-2021 11 147728 0 1 ...
Active listening is one of the important soft skills in several aspects of life, especially communication. Effective communication is highly dependent on a persons skills in sending and receiving ...
What's Remote File Transfer?There are lots of ways to access files remotely these days, but one of the most effective methods is still through remote file transfer software. These tools let you ...
Massachusetts strong and diverse economy not only means plenty of jobs in all areas of human resources, but plenty of high-paying jobs for everyone from entry-level HR assistants to senior-level HR ...
Blog/Packing Lists/Weekend Trip Packing List: What to Bring for a 3-Day GetawayPacking ListsWeekend Trip Packing List: What to Bring for a 3-Day GetawayOutbreaker Backpack $349Table of Contents3-Day ...