0% found this document useful (0 votes)
35 views5 pages

Java ArrayList: Creation and Management

ArrayList is a resizable list that dynamically increases in size as elements are added. It uses an internal array to store elements and resizes the array as needed. ArrayList allows dynamic resizing, reducing memory usage compared to arrays which have a fixed size. Common operations on ArrayList include adding, removing, and traversing elements. Elements can be retrieved and modified using their index. The list can also be sorted using Collections.sort.

Uploaded by

Priyansh Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views5 pages

Java ArrayList: Creation and Management

ArrayList is a resizable list that dynamically increases in size as elements are added. It uses an internal array to store elements and resizes the array as needed. ArrayList allows dynamic resizing, reducing memory usage compared to arrays which have a fixed size. Common operations on ArrayList include adding, removing, and traversing elements. Elements can be retrieved and modified using their index. The list can also be sorted using Collections.sort.

Uploaded by

Priyansh Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ARRAYLIST IN JAVA

ArrayList is part of the collections framework. ArrayList is a List and implements the [Link] interface.

ArrayList is a better alternative to Arrays, especially if you are not sure about the array size. Unlike
array which have a fixed size, ArrayList can grow in size when needed.

Internally ArrayList also uses arrays to store data. When it reaches the current capacity and needs to
grow, a new array is created and elements are copied from the old array to the new array. In the newer
code, ArrayList is used along with generics.

ArrayList has many advantages over arrays such as:

 It dynamically resizes based on the number of elements in the list.

 It reduces the memory footprint. In case of arrays, we need to allocate memory upfront as we cannot
change later. So extra memory is allocated even if we don't use it.

If you are sure about the number of elements or if primitive data types are the elements we can use
Arrays instead.

The ArrayList class is similar to a Vector as both can grow in size as needed. But unlike Vector, ArrayList
is not synchronized. ArrayList is always preferred over a Vector. There are many ways through which we
can make an ArrayList thread safe like [Link](theArrayList) or we can use a use a
CopyOnWriteArrayList.

If simultaneous overwrite occurs in an ArrayList, a ConcurrentModificationException exception is thrown.


Synchronizing a class when not required can affect the performance.

Creating ArrayList
There are three constructors for creating an ArrayList.

When you create an ArrayList using the constructor ArrayList(), the internal array for storage is created
with a size 10.
The constructor ArrayList(int initialCapacity) allows us to set the initial capacity.
The constructor ArrayList( Collection) constructs a list containing the elements of the specified
collection.
In the newer code, ArrayList is used along with generics:

ArrayList<String> list = new ArrayList<String>();

ArrayList<String> list = new ArrayList<String>(20);


ArrayList<String> list = new ArrayList<String>(myCollection);

Adding elements
We can add elements to an array list using the add or addAll methods that appends one or more
elements to the end of the list, or an overloaded add or addAll with an index argument that inserts one
or more elements at a position within the list.
ArrayList<String> names = new ArrayList<String>();

[Link]("Heartin");

[Link]("Sneha");

[Link](1, "Jacob");

[Link](names);

ArrayList<String> namesNew = new ArrayList<String>();

[Link](names);

[Link](namesNew);

[Link](2,names);

[Link](namesNew);

This will print:

[Heartin, Jacob, Sneha]

[Heartin, Jacob, Sneha]

[Heartin, Jacob, Heartin, Jacob, Sneha, Sneha]

Changing elements
We can modify an element of a list using the set method.
[Link](1, "June");

Retrieving elements and index


To retrieve an element at a given position, use the get method.
[Link]([Link](2));

The index of the first occurrence of an element can be obtained using the indexOf method.
[Link]([Link]("Jacob"));
-1 is returned if the element is not present. The index of the last occurrence of an element can be
obtained using lastIndexOf method.

Traversing
We can traverse an ArrayList using:
 Simple for statement

 for-each statement

 Iterator

 ListIterator

Example - for each loop


for(String str : names)

[Link](str);

Example – for loop


for(int i=0; i<[Link]();i++)

[Link]([Link](i));

Example – Iterator
Iterator<String> iterator = [Link]();

while ([Link]()) {
[Link]([Link]());

Example – ListIterator
ListIterator can be used to traverse the list in both directions.

ListIterator<String> listIterator = [Link]();

while ([Link]()) {

[Link]([Link]());

while([Link]()) {

[Link]([Link]());

This will print:

Heartin

June

Sneha

Sneha

June

Heartin

First while loop will traverse in the forward direction from first reaching the last and then the second while
loop will traverse in the reverse direction.

Note that if we put the hasPrevious while loop before the next while loop, output will be only:

Heartin

June

Sneha
Sorting
[Link] method can be used to sort an ArrayList:
[Link](names);

Removing elements
The clear method will remove all elements. The remove method removes a single element and
theremoveAll method removes all values in a given collection from the list. The retainAll method retains
all values in a given collection from the list.
[Link](0);

[Link]("Jacob");

[Link](names);

[Link](names);

[Link]();

Source : [Link]

Common questions

Powered by AI

Methods available for modifying elements in an ArrayList include the 'set' method, which changes the element at a specified index to a new value . For managing element positions such as retrieving them, the 'get' method is used to access elements at specific indexes, while 'indexOf' and 'lastIndexOf' methods are used to find the index of the first and last occurrences of an element, respectively, returning -1 if the element is not present .

ArrayLists support traversal through simple for loops, for-each statements, Iterators, and ListIterators. Simple for loops provide direct index-based access, whereas for-each loops offer an enhanced syntax for iterating over collections . Iterators are useful for forward traversal and offer methods like 'hasNext' and 'next' for safe navigation. ListIterators extend Iterators by allowing bidirectional traversal with 'hasPrevious' and 'previous' methods, making them suitable for scenarios requiring backward navigation .

ArrayList is generally preferred over Vector because ArrayList is not synchronized, making it more efficient for most use cases. Synchronization in Vector, though helpful in making it thread-safe, can affect performance negatively when not needed . Thread safety in ArrayLists can be ensured by using Collections.synchronizedList() or by using a CopyOnWriteArrayList, both of which provide safe concurrent access .

Elements can be added to an ArrayList using the 'add' and 'addAll' methods. The 'add' method appends individual elements to the end of the list or inserts them at a specific index if provided, thereby altering the list by shifting subsequent elements . The 'addAll' method appends a collection of elements to the end of the list or inserts them at a specified position, restructuring the list as required by shifting subsequent elements as well .

ArrayList manages its capacity by maintaining an internal array to store elements. When the number of elements exceeds current capacity, ArrayList creates a new array with increased capacity, usually larger, and transfers the elements to this new array . This resizing strategy optimizes memory usage by ensuring that ArrayList can grow as needed without allocating excessive memory upfront, unlike arrays. However, frequent resizing can temporarily double memory usage during array copying, which needs consideration in memory-constrained environments .

ListIterator enhances list traversal by enabling bidirectional navigation, allowing for both forward and backward iteration through the list . This is beneficial in scenarios where elements need to be revisited or corrected during iteration, such as editing or reversal operations within a single pass. Additionally, ListIterator provides methods for adding elements and querying the index position, which are advantageous for more complex list manipulation tasks .

ArrayList differs from arrays by being dynamically resizable, which means it can grow in size as needed, unlike arrays that have a fixed size . Internally, ArrayList uses arrays to store its elements. When an ArrayList reaches its current capacity and needs to grow, it creates a new array and copies the elements from the old array to the new array, allowing dynamic resizing .

Generics play a crucial role in using ArrayLists by allowing the specification of the type of elements it can store, enhancing compile-time type checking and safety . This prevents runtime errors related to type casting and increases usability by ensuring that only elements of the correct type are added, making the code more robust and easier to maintain. Generics also eliminate the need for explicit type casting when retrieving elements from an ArrayList, simplifying generic code and reducing the potential for errors .

The 'remove' method in ArrayList removes a single element specified by index or object, effectively reducing the list size by one and shifting subsequent elements . In contrast, 'removeAll' removes all elements that are also contained in a specified collection, which is used to remove multiple elements en masse, typically when filtering or cleaning up data sets .

Synchronizing an ArrayList can have negative performance implications because it introduces overhead by ensuring that only one thread can modify the list at a time, leading to reduced concurrency . This can be mitigated by using alternative collections like CopyOnWriteArrayList for scenarios where synchronization is required but can be managed more efficiently, as it avoids locking by working with separate copies of data for each write operation .

You might also like