Fixed size ArrayList java

In Java programming, there are two ways to create an array.

  • Array: Is a simple fixed-size data structure which requires a size at the time of creation.

  • ArrayList: Is a dynamic sized data structure which doesn’t require a specific size at the time of initialization.

An Array can contain both primitive data types or objects of a class depending on the definition of the array. But it has a fixed size.

Example

// Importing the required libraries import java.util.Arrays; class Array { public static void main[String args[]] { /* ...........Array............. */ // Fixed size. // Cannot add more than 3 elements. int[] arr = new int[3]; arr[0] = 5; arr[1] = 6; arr[2] = 10; // Printing System.out.println[Arrays.toString[arr]]; } }

An ArrayList can’t be created for primitive data types. It only contains an object. It has the ability to grow and shrink dynamically.

  • Remember that in Java, every primitive data type has a wrapper class. | Primitive | Wrapper class | | — | — | | int | Integer | | short | Short | | byte | Byte | | char | Character | | float | Float |

Example

// Importing required libraries import java.util.ArrayList; class Array_List { public static void main[String args[]] { /*............ArrayList..............*/ // Variable size. // Can add more elements. ArrayList arr = new ArrayList[]; arr.add[5]; arr.add[9]; arr.add[11]; // Printing System.out.println[arr]; } }

The 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:

  1. Create a new backing array with more size than previous array.
  2. 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

Let us know if you liked the post. That’s the only way we can improve.

public: static System::Collections::ArrayList ^ FixedSize[System::Collections::ArrayList ^ list]; public static System.Collections.ArrayList FixedSize [System.Collections.ArrayList list]; static member FixedSize : System.Collections.ArrayList -> System.Collections.ArrayList Public Shared Function FixedSize [list As ArrayList] As ArrayList ArrayList

An ArrayList wrapper with a fixed size.

Examples

The following code example shows how to create a fixed-size wrapper around an ArrayList.

using namespace System; using namespace System::Collections; void PrintValues[ IEnumerable^ myList, char mySeparator ]; int main[] { // Creates and initializes a new ArrayList. ArrayList^ myAL = gcnew ArrayList; myAL->Add[ "The" ]; myAL->Add[ "quick" ]; myAL->Add[ "brown" ]; myAL->Add[ "fox" ]; myAL->Add[ "jumps" ]; myAL->Add[ "over" ]; myAL->Add[ "the" ]; myAL->Add[ "lazy" ]; myAL->Add[ "dog" ]; // Create a fixed-size wrapper around the ArrayList. ArrayList^ myFixedSizeAL = ArrayList::FixedSize[ myAL ]; // Display whether the ArrayLists have a fixed size or not. Console::WriteLine[ "myAL {0}.", myAL->IsFixedSize ? [String^]"has a fixed size" : "does not have a fixed size" ]; Console::WriteLine[ "myFixedSizeAL {0}.", myFixedSizeAL->IsFixedSize ? [String^]"has a fixed size" : "does not have a fixed size" ]; Console::WriteLine[]; // Display both ArrayLists. Console::WriteLine[ "Initially," ]; Console::Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console::Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; // Sort is allowed in the fixed-size ArrayList. myFixedSizeAL->Sort[]; // Display both ArrayLists. Console::WriteLine[ "After Sort," ]; Console::Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console::Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; // Reverse is allowed in the fixed-size ArrayList. myFixedSizeAL->Reverse[]; // Display both ArrayLists. Console::WriteLine[ "After Reverse," ]; Console::Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console::Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; // Add an element to the standard ArrayList. myAL->Add[ "AddMe" ]; // Display both ArrayLists. Console::WriteLine[ "After adding to the standard ArrayList," ]; Console::Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console::Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; Console::WriteLine[]; // Adding or inserting elements to the fixed-size ArrayList throws an exception. try { myFixedSizeAL->Add[ "AddMe2" ]; } catch [ Exception^ myException ] { Console::WriteLine[ "Exception: {0}", myException ]; } try { myFixedSizeAL->Insert[ 3, "InsertMe" ]; } catch [ Exception^ myException ] { Console::WriteLine[ "Exception: {0}", myException ]; } } void PrintValues[ IEnumerable^ myList, char mySeparator ] { IEnumerator^ myEnum = myList->GetEnumerator[]; while [ myEnum->MoveNext[] ] { Object^ obj = safe_cast[myEnum->Current]; Console::Write[ "{0}{1}", mySeparator, obj ]; } Console::WriteLine[]; } /* This code produces the following output. myAL does not have a fixed size. myFixedSizeAL has a fixed size. Initially, Standard : The quick brown fox jumps over the lazy dog Fixed size: The quick brown fox jumps over the lazy dog After Sort, Standard : brown dog fox jumps lazy over quick the The Fixed size: brown dog fox jumps lazy over quick the The After Reverse, Standard : The the quick over lazy jumps fox dog brown Fixed size: The the quick over lazy jumps fox dog brown After adding to the standard ArrayList, Standard : The the quick over lazy jumps fox dog brown AddMe Fixed size: The the quick over lazy jumps fox dog brown AddMe Exception: System.NotSupportedException: Collection was of a fixed size. at System.Collections.FixedSizeArrayList.Add[Object obj] at SamplesArrayList.Main[] Exception: System.NotSupportedException: Collection was of a fixed size. at System.Collections.FixedSizeArrayList.Insert[Int32 index, Object obj] at SamplesArrayList.Main[] */ using System; using System.Collections; public class SamplesArrayList { public static void Main[] { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList[]; myAL.Add[ "The" ]; myAL.Add[ "quick" ]; myAL.Add[ "brown" ]; myAL.Add[ "fox" ]; myAL.Add[ "jumps" ]; myAL.Add[ "over" ]; myAL.Add[ "the" ]; myAL.Add[ "lazy" ]; myAL.Add[ "dog" ]; // Create a fixed-size wrapper around the ArrayList. ArrayList myFixedSizeAL = ArrayList.FixedSize[ myAL ]; // Display whether the ArrayLists have a fixed size or not. Console.WriteLine[ "myAL {0}.", myAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size" ]; Console.WriteLine[ "myFixedSizeAL {0}.", myFixedSizeAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size" ]; Console.WriteLine[]; // Display both ArrayLists. Console.WriteLine[ "Initially," ]; Console.Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console.Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; // Sort is allowed in the fixed-size ArrayList. myFixedSizeAL.Sort[]; // Display both ArrayLists. Console.WriteLine[ "After Sort," ]; Console.Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console.Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; // Reverse is allowed in the fixed-size ArrayList. myFixedSizeAL.Reverse[]; // Display both ArrayLists. Console.WriteLine[ "After Reverse," ]; Console.Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console.Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; // Add an element to the standard ArrayList. myAL.Add[ "AddMe" ]; // Display both ArrayLists. Console.WriteLine[ "After adding to the standard ArrayList," ]; Console.Write[ "Standard :" ]; PrintValues[ myAL, ' ' ]; Console.Write[ "Fixed size:" ]; PrintValues[ myFixedSizeAL, ' ' ]; Console.WriteLine[]; // Adding or inserting elements to the fixed-size ArrayList throws an exception. try { myFixedSizeAL.Add[ "AddMe2" ]; } catch [ Exception myException ] { Console.WriteLine["Exception: " + myException.ToString[]]; } try { myFixedSizeAL.Insert[ 3, "InsertMe" ]; } catch [ Exception myException ] { Console.WriteLine["Exception: " + myException.ToString[]]; } } public static void PrintValues[ IEnumerable myList, char mySeparator ] { foreach [ Object obj in myList ] Console.Write[ "{0}{1}", mySeparator, obj ]; Console.WriteLine[]; } } /* This code produces the following output. myAL does not have a fixed size. myFixedSizeAL has a fixed size. Initially, Standard : The quick brown fox jumps over the lazy dog Fixed size: The quick brown fox jumps over the lazy dog After Sort, Standard : brown dog fox jumps lazy over quick the The Fixed size: brown dog fox jumps lazy over quick the The After Reverse, Standard : The the quick over lazy jumps fox dog brown Fixed size: The the quick over lazy jumps fox dog brown After adding to the standard ArrayList, Standard : The the quick over lazy jumps fox dog brown AddMe Fixed size: The the quick over lazy jumps fox dog brown AddMe Exception: System.NotSupportedException: Collection was of a fixed size. at System.Collections.FixedSizeArrayList.Add[Object obj] at SamplesArrayList.Main[] Exception: System.NotSupportedException: Collection was of a fixed size. at System.Collections.FixedSizeArrayList.Insert[int index, Object obj] at SamplesArrayList.Main[] */ Imports System.Collections Public Class SamplesArrayList Public Shared Sub Main[] ' Creates and initializes a new ArrayList. Dim myAL As New ArrayList[] myAL.Add["The"] myAL.Add["quick"] myAL.Add["brown"] myAL.Add["fox"] myAL.Add["jumps"] myAL.Add["over"] myAL.Add["the"] myAL.Add["lazy"] myAL.Add["dog"] ' Create a fixed-size wrapper around the ArrayList. Dim myFixedSizeAL As ArrayList = ArrayList.FixedSize[myAL] ' Display whether the ArrayLists have a fixed size or not. Dim msg As String If myAL.IsFixedSize Then msg = "has a fixed size" Else msg = "does not have a fixed size" End If Console.WriteLine["myAL {0}.", msg] If myFixedSizeAL.IsFixedSize Then msg = "has a fixed size" Else msg = "does not have a fixed size" End If Console.WriteLine["myFixedSizeAL {0}.", msg] Console.WriteLine[] ' Display both ArrayLists. Console.WriteLine["Initially,"] Console.Write["Standard :"] PrintValues[myAL, " "c] Console.Write["Fixed size:"] PrintValues[myFixedSizeAL, " "c] ' Sort is allowed in the fixed-size ArrayList. myFixedSizeAL.Sort[] ' Display both ArrayLists. Console.WriteLine["After Sort,"] Console.Write["Standard :"] PrintValues[myAL, " "c] Console.Write["Fixed size:"] PrintValues[myFixedSizeAL, " "c] ' Reverse is allowed in the fixed-size ArrayList. myFixedSizeAL.Reverse[] ' Display both ArrayLists. Console.WriteLine["After Reverse,"] Console.Write["Standard :"] PrintValues[myAL, " "c] Console.Write["Fixed size:"] PrintValues[myFixedSizeAL, " "c] ' Add an element to the standard ArrayList. myAL.Add["AddMe"] ' Display both ArrayLists. Console.WriteLine["After adding to the standard ArrayList,"] Console.Write["Standard :"] PrintValues[myAL, " "c] Console.Write["Fixed size:"] PrintValues[myFixedSizeAL, " "c] Console.WriteLine[] ' Adding or inserting elements to the fixed-size ArrayList throws an exception. Try myFixedSizeAL.Add["AddMe2"] Catch myException As Exception Console.WriteLine["Exception: " + myException.ToString[]] End Try Try myFixedSizeAL.Insert[3, "InsertMe"] Catch myException As Exception Console.WriteLine["Exception: " + myException.ToString[]] End Try End Sub Public Shared Sub PrintValues[myList As IEnumerable, mySeparator As Char] Dim obj As [Object] For Each obj In myList Console.Write["{0}{1}", mySeparator, obj] Next obj Console.WriteLine[] End Sub End Class ' This code produces the following output. ' ' myAL does not have a fixed size. ' myFixedSizeAL has a fixed size. ' ' Initially, ' Standard : The quick brown fox jumps over the lazy dog ' Fixed size: The quick brown fox jumps over the lazy dog ' After Sort, ' Standard : brown dog fox jumps lazy over quick the The ' Fixed size: brown dog fox jumps lazy over quick the The ' After Reverse, ' Standard : The the quick over lazy jumps fox dog brown ' Fixed size: The the quick over lazy jumps fox dog brown ' After adding to the standard ArrayList, ' Standard : The the quick over lazy jumps fox dog brown AddMe ' Fixed size: The the quick over lazy jumps fox dog brown AddMe ' ' Exception: System.NotSupportedException: Collection was of a fixed size. ' at System.Collections.FixedSizeArrayList.Add[Object obj] ' at SamplesArrayList.Main[] ' Exception: System.NotSupportedException: Collection was of a fixed size. ' at System.Collections.FixedSizeArrayList.Insert[Int32 index, Object obj] ' at SamplesArrayList.Main[]

Remarks

This wrapper can be used to prevent additions to and deletions from the original ArrayList. The elements can still be modified or replaced.

A collection with a fixed size is simply a collection with a wrapper that prevents adding and removing elements; therefore, if changes are made to the underlying collection, including the addition or removal of elements, the fixed-size collection reflects those changes.

This method is an O[1] operation.

Applies to

Video liên quan

Chủ Đề