In this article, we are going to learn about ArrayList. It is one of the collection types in C# that allows us a flexible option to store data.
Let’s begin!
Collection in C#
In C#, a collection is a grouping of related objects that provides ways to store, manipulate, and manage data. It allows us to organize and access multiple elements as a single unit.
We have several different types of collections like ArrayList
, List
, Dictionary
, Queue
, Stack
, etc., each with its own feature and usage.
ArrayList in C#
ArrayList
in C# is a dynamic array that can store objects of any type. It provides us the flexibility to handle collections as it is resizable.
Let’s delve into ArrayList
and explore its features along with some coding.
ArrayList Methods in C#
Let’s look at some commonly used methods of ArrayList
to see how we can use them to add, remove, sort, clone and search the elements.
Adding Elements to an ArrayList
We can add elements in an ArrayList
using the Add()
method:
var arrayList = new ArrayList(); arrayList.Add("Hello"); arrayList.Add(123); arrayList.Add(56.89); Assert.Equal(3, arrayList.Count);
Here, we have three different values of different types. The first is a string
, the second an int
, and the third a double
.
This represents the non-generic collection that doesn’t support type casting. Hence, we can add any value to the ArrayList
.
However, we can also add elements to an ArrayList
using an object initializer instead of using the Add()
method:
var arrayList = new ArrayList { "Hello", 123, 56.89 }; Assert.Equal(3, arrayList.Count);
To add multiple elements from a collection to an existing ArrayList
, we can utilize the AddRange()
method:
var arrayList = new ArrayList { "Hello", 123, 56.89 }; var secondArrayList = new ArrayList { "World", 456, 59.95 }; arrayList.AddRange(secondArrayList); Assert.Equal(new ArrayList() { "Hello", 123, 56.89, "World", 456, 59.95 }, arrayList);
Inserting Elements in an ArrayList
To insert an element at the specified index into an ArrayList
, we use the Insert()
method:
var arrayList = new ArrayList { "Hello", 123, 56.89 }; arrayList.Insert(1, "World"); Assert.Equal("World", arrayList[1]);
We can use the InsertRange()
method to insert a collection in an ArrayList
at a specified index:
var arrayList = new ArrayList { "Hello", 123, 56.89 }; var secondArrayList = new ArrayList { "World", 456, 59.95 }; arrayList.InsertRange(1, secondArrayList); Assert.Equal(new ArrayList() { "Hello", "World", 456, 59.95, 123, 56.89 }, arrayList);
Removing Elements From an ArrayList
We can remove elements from an ArrayList
using the Remove()
method. It removes the first occurrence of the specified item:
var arrayList = new ArrayList() { "Hello", 42, "World" }; arrayList.Remove(42); Assert.False(arrayList.Contains(42));
To remove the element at the specified index, we use the RemoveAt()
method:
var arrayList = new ArrayList() { "Apple", "Banana", "Orange" }; arrayList.RemoveAt(1); Assert.False(arrayList.Contains("Banana"));
For removing elements within the specified range, we can use the RemoveRange()
method:
var arrayList = new ArrayList() { 1, 2, 3, 4, 5 }; arrayList.RemoveRange(1, 3); Assert.Equal(new ArrayList() { 1, 5 }, arrayList);
We can use the RemoveRange()
method to remove the specified number of elements, starting from a given index.
The first argument is the index starting from where we want to remove the elements. The second argument is the number of elements we want to remove from the ArrayList
.
If we want to clear all the elements from the ArrayList
, we can use the Clear()
method:
var arrayList = new ArrayList() { 1, 2, 3, 4, 5 }; arrayList.Clear(); Assert.Empty(arrayList);
Accessing Elements From an ArrayList
To access any element from an ArrayList
, we can use its index:
var arrayList = new ArrayList() { "Hello", 42, "World" }; var element = arrayList[2]; Assert.Equal("World", element);
Sorting an ArrayList
We can sort the elements of an ArrayList
using the Sort()
method:
var arrayList = new ArrayList() { 5, 2, 8, 1 }; var expected = new ArrayList() { 1, 2, 5, 8 }; arrayList.Sort(); Assert.Equal(expected, arrayList);
By default, it sorts the elements in ascending order.
To reverse the order of the elements in the given ArrayList
, we can use the Reverse()
method:
var arrayList = new ArrayList() { "Apple", "Banana", "Orange", "Grapes" }; arrayList.Reverse(); Assert.Equal(new ArrayList() { "Grapes", "Orange", "Banana", "Apple" }, arrayList);
It is important to note that these sorting methods sort the ArrayList
components according to their natural order, taking into account their data types. Thus, if the ArrayList
contains elements of different data types, the sort may not produce the expected results.
So, we should use the generic List<T>
collection to overcome this limitation and achieve type-safe sorting.
Searching for Elements in an ArrayList
To search for elements in an ArrayList
, we use the IndexOf()
method. It returns the index of the first occurrence of a specified element:
var arrayList = new ArrayList() { "Apple", "Banana", "Orange" }; var expectedIndex = 1; var actualIndex = arrayList.IndexOf("Banana"); Assert.Equal(expectedIndex, actualIndex);
If we want to check if the ArrayList
contains a specified element, we can use the Contains()
method:
var arrayList = new ArrayList() { "Apple", "Banana", "Orange" }; Assert.True(arrayList.Contains("Banana")); Assert.False(arrayList.Contains("Mango"));
To get the index of the last occurrence of an element in the ArrayList
, we can use the LastIndexOf()
method:
var arrayList = new ArrayList() { "Apple", "Banana", "Orange", "Banana", "Grapes" }; var index = arrayList.LastIndexOf("Banana"); Assert.Equal(3, index);
Cloning an ArrayList
To clone an ArrayList
we can use the Clone()
method. It creates a shallow copy of the ArrayList
:
var originalArrayList = new ArrayList() { 1, 2, 3, "Hello" }; var clonedArrayList = (ArrayList)originalArrayList.Clone(); Assert.Equal(originalArrayList, clonedArrayList); Assert.NotSame(originalArrayList, clonedArrayList);
The shallow copy refers to a new ArrayList
object that contains references to the same elements as the original ArrayList
.
Get Elements Within Range From an ArrayList
To get a specified number of elements from any given index from the ArrayList
, we can use the GetRange()
method:
var arrayList = new ArrayList() { 1, 2, 3, 4, 5 }; var arrayListRange = arrayList.GetRange(1, 3); Assert.Equal(new ArrayList { 2, 3, 4 }, arrayListRange);
Comparing ArrayList With Other Collections in C#
When comparing the ArrayList
with other collections, several factors come into play.
Type Safety: Unlike generic collections, such as List<T>
, HashSet<T>
, or Dictionary<TKey, TValue>
, the ArrayList
is not type-safe and can store objects of any type. However, this might lead to potential runtime errors if we access incorrect types.
Performance: The ArrayList
can have performance limitations when compared to specialized collections. Since it stores objects as System.Object
, we require boxing and unboxing operations. Thus, retrieving or modifying elements can impact performance.
Features: The ArrayList
lacks several features that the specialized collections provide. We cannot easily perform set operations like union, intersection, or distinct values using ArrayList
. Whereas, specialized collections offer specific methods and functionalities tailored for different scenarios.
Flexibility: The ArrayList
can handle objects of any type, making it more flexible than some specialized collections. However, this flexibility comes at the cost of type safety and performance.
In most cases, it is recommended to use generic collections List<T>
or specialized collections based on specific requirements. They provide better performance, type safety, and additional features. However, if we need to work with a mixed collection of objects of various types without requiring strict type checking, an ArrayList
can still serve a purpose.
Advice and Notes Regarding ArrayList
When we are working with the ArrayList
class, it is essential to follow best practices to ensure efficient and reliable code. Here are some recommended practices:
Specifying initial capacity: If we know the approximate number of elements the ArrayList
will hold, then it is recommended that we set its initial capacity using the Capacity
property. By doing so, we can avoid unnecessary resizing operations, improving performance.
Avoiding mixing types: To maintain code clarity and prevent runtime errors, we should avoid storing different types of objects in the same ArrayList
. Instead, we should use a specialized collection or create a custom class to encapsulate related data.
Favoring type-specific collections: If we have a collection of a specific type, we should prefer using a collection designed for that type. For instance, using List<string>
for string elements or Dictionary<int, string>
for key-value pairs.
Using explicit casting: When retrieving elements from an ArrayList
, we should use explicit casting ((T)element
) to ensure type safety. We should avoid relying on implicit casting, as it can lead to runtime errors.
Considering collection interface: Instead of using ArrayList
directly, we should consider using ICollection<T>
or IEnumerable<T>
interfaces. Thus, allowing us to do easier swapping of different collection implementations.
Being mindful of performance impact: Since the ArrayList
performs boxing and unboxing operations, we should be aware of the potential impact on performance. Especially, in scenarios with large data sets or frequent modifications we should consider using specialized collections for improved performance.
Conclusion
In this article, we learned about ArrayList
, different ways to work with ArrayList
with some examples, a comparison of ArrayList
with other collections available and best practices for using ArrayList
in C#.