TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# ArrayList Examples

Use the ArrayList type from System.Collections. ArrayList is a resizable array.
ArrayList. The world of animals is vast. Consider the centipede. It has many legs. Some centipedes have more legs than others—the exact count varies.
An ArrayList too can be found with a various number of elements. This collection dynamically resizes. It grows in capacity as elements are added (if space is needed).
Add method. This appends a new element object to the end. We can keep adding elements to the collection until memory runs out. The objects are stored in the managed heap.

Here: We see a complete console program. When you run it, 3 elements are added to the ArrayList.

Elements: The first element is a string containing "One." The last element is "Three."

C# program that uses ArrayList using System.Collections; class Program { static void Main() { // Create an ArrayList and add 3 elements. ArrayList list = new ArrayList(); list.Add("One"); list.Add("Two"); list.Add("Three"); } }
Arguments. It is easy to pass ArrayList as an argument. However, in the receiving function, you have to know (or find out) the type of each element.

Next: In this program we pass the ArrayList as an argument to the Example() method.

Info: You can also use the ArrayList as a return value. It is usually best to reuse the same ArrayList.

C# program that uses ArrayList parameter using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList and add two ints. // ArrayList list = new ArrayList(); list.Add(5); list.Add(7); // // Use ArrayList with method. // Example(list); } static void Example(ArrayList list) { foreach (int i in list) { Console.WriteLine(i); } } } Output 5 7
Combine. We can use AddRange to combine two ArrayLists. Internally, AddRange uses the Array.Copy or CopyTo methods, which have better performance than some loops.Array.Copy

Here: The first ArrayList has two elements added to it. Next, the second ArrayList has two elements added.

Then: The second ArrayList is appended to the first using the AddRange method. The example finally shows the output.

C# program that uses Add and AddRange using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with two values. // ArrayList list = new ArrayList(); list.Add(5); list.Add(7); // // Second ArrayList. // ArrayList list2 = new ArrayList(); list2.Add(10); list2.Add(13); // // Add second ArrayList to first. // list.AddRange(list2); // // Display the values. // foreach (int i in list) { Console.WriteLine(i); } } } Output 5 7 10 13
Count. This is a virtual property. When you use Count, no counting is actually done. Instead a cached field value is returned. This means that Count is fairly fast.

Here: The example shows the Count property. It also shows the Clear method, and how this affects the count.

Int: The Count property returns an int. This will always be a positive value. No calculation takes place in the property itself.

Int, uint

Clear: You can call the instance method Clear on your ArrayList. Internally, this calls the Array.Clear method.

Array.Clear

Sometimes: Code is clearer if you instead create a new ArrayList. This may also affect performance.

C# program that uses Count using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with two values. // ArrayList list = new ArrayList(); list.Add(9); list.Add(10); // // Show number of elements in ArrayList. // Console.WriteLine(list.Count); // // Clear the ArrayList. // list.Clear(); // // Show count again. // Console.WriteLine(list.Count); } } Output 2 0
Sort, reverse. Many dynamic arrays (such as ArrayList) must be frequently sorted. We call the instance Sort method and then Reverse. These methods work in-place.

Tip: You can sort subsets (ranges) of elements in your ArrayList using the third overload. This is useful in rare situations.

Also: You can Reverse only a range of your ArrayList. This is useful even less often.

Note: The Sort method in the base class library is an instance method (with no parameters) on ArrayList.

Elements: The ArrayList Sort method works on different element types. The example here shows strings.

C# program that sorts ArrayList and reverses using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with four strings. // ArrayList list = new ArrayList(); list.Add("Cat"); list.Add("Zebra"); list.Add("Dog"); list.Add("Cow"); // // Sort the ArrayList. // list.Sort(); // // Display the ArrayList elements. // foreach (string value in list) { Console.WriteLine(value); } // // Reverse the ArrayList. // list.Reverse(); // // Display the ArrayList elements again. // foreach (string value in list) { Console.WriteLine(value); } } } Output Cat Cow Dog Zebra Zebra Dog Cow Cat
Insert, Remove. Here we insert and remove elements in an ArrayList. We see the RemoveAt method for erasing a single element, and then Insert and RemoveRange.

Tip: The first argument to Insert is the position: this is equivalent to the index of the element.

C# program that uses Insert and Remove using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with three strings. // ArrayList list = new ArrayList(); list.Add("Dot"); list.Add("Net"); list.Add("Perls"); // // Remove middle element in ArrayList. // list.RemoveAt(1); // It becomes [Dot, Perls] // // Insert word at the beginning of ArrayList. // list.Insert(0, "Carrot"); // It becomes [Carrot, Dot, Perls] // // Remove first two words from ArrayList. // list.RemoveRange(0, 2); // // Display the result ArrayList. // foreach (string value in list) { Console.WriteLine(value); // <-- "Perls" } } } Output Perls
Loop. The for-loop is popular and useful. We need to cast elements after accessing them. The "i" part in the example shows how to use the indexer on the ArrayList.Indexer

Cast: The "as" cast in C# is probably the best way to cast reference types such as string.

As

Tip: After you cast, you can check the result for null before using the variable, to see if the cast succeeded.

C# program that uses ArrayList and for using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with three strings. // ArrayList list = new ArrayList(); list.Add("man"); list.Add("woman"); list.Add("plant"); // // Loop over ArrayList. // for (int i = 0; i < list.Count; i++) { string value = list[i] as string; Console.WriteLine(value); } } } Output man woman plant
GetRange. This will return a subset of the original ArrayList in a new ArrayList. This is ideal when you know a certain part of your ArrayList has a different purpose or behavior.

SetRange: The SetRange method on ArrayList is also useful when you need to replace a range.

However: I have not found SetRange to be useful, as often you will just want to replace elements in a for-loop.

C# program that uses GetRange using System; using System.Collections; class Program { static void Main() { // // Create an ArrayList with 4 strings. // ArrayList list = new ArrayList(); list.Add("fish"); list.Add("amphibian"); list.Add("bird"); list.Add("plant"); // // Get last two elements in ArrayList. // ArrayList range = list.GetRange(2, 2); // // Display the elements. // foreach (string value in range) { Console.WriteLine(value); // bird, plant } } } Output bird plant
IndexOf. The IndexOf and LastIndexOf methods on ArrayList are similar to those on strings. You pass in the value you are looking for, the start index, the number of elements to search.

Info: IndexOf will return -1 if the element could not be located. This value must be specially tested.

IndexOf
C# program that uses ArrayList IndexOf using System; using System.Collections; class Program { static void Main() { ArrayList list = new ArrayList(); list.Add(5); list.Add(7); // Call IndexOf. int result = list.IndexOf(7); Console.WriteLine("RESULT: {0}", result); Console.WriteLine("NOT FOUND: {0}", list.IndexOf(900)); } } Output RESULT: 1 NOT FOUND: -1
Benchmark, List, ArrayList. Here we compare the performance of List (a generic collection) to ArrayList. We add, remove, test and clear each collection.

Version 1: This version of the code uses the List from System.Collections.Generic. Many iterations are run.

Version 2: Here we use the ArrayList from System.Collections. We perform the same actions as in version 1.

Result: List performs with more than twice the speed of ArrayList. It performs this simple benchmark faster.

Unboxing: There is a performance penalty in using ArrayList, particularly on value types. This is because boxing (and unboxing) occurs.

C# program that benchmarks List, ArrayList using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; class Program { static void Main() { List<int> list = new List<int>(); ArrayList array = new ArrayList(); const int max = 1000000; var s1 = Stopwatch.StartNew(); // Version 1: use List. for (int i = 0; i < max; i++) { list.Add(10); list.Add(20); list.Add(30); list.Remove(30); if (list[list.Count - 1] != 20) { return; } list.Clear(); } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use ArrayList. for (int i = 0; i < max; i++) { array.Add(10); array.Add(20); array.Add(30); array.Remove(30); if ((int)array[array.Count - 1] != 20) { return; } array.Clear(); } s2.Stop(); Console.WriteLine(s1.Elapsed.TotalMilliseconds); Console.WriteLine(s2.Elapsed.TotalMilliseconds); Console.Read(); } } Output 67.4821 ms, List add, remove, test, clear 151.8429 ms, ArrayList add, remove, test, clear
Performance, sort. The ArrayList Sort method ends up in an internal TrySZSort or QuickSort method when it doesn't throw an exception.

Note: TrySZSort is optimized for one-dimensional arrays, also known as "Zero" arrays or vectors.

Info: The TrySZSort method used in the base class libraries is implemented in native code. It has been heavily optimized.

Thus: Using Sort on ArrayList or on Array is faster than most custom implementations.

Convert. Arrays offer more performance and compatibility, so you will want to convert ArrayLists to arrays. We use casting to convert an ArrayList to an array.Convert ArrayList, Array
List versus ArrayList. It is usually better to use List. But older applications may be using ArrayList. And it is often best not to have to rewrite them.List

Note: Lists not only avoid boxing or unboxing, but they also lead to clearer and less bug-prone code.

And: With List, the compiler can check your code for type integrity before runtime. This improves reliability.

BinarySearch. This method implements the binary searching algorithm. This uses a "divide and conquer" approach to finding the correct element. It only works on presorted data.

Thus: Never use BinarySearch if your ArrayList might not be already sorted. The results could be invalid.

BinarySearch List
A review. ArrayList holds objects. It stores elements of type object—casting is needed. We end up with as-casts, numeric casts to test elements. Code becomes messy. Use a List instead.
ArrayList is a collection that is best avoided. But it is often used in older legacy programs—so it must be supported. Newer .NET Framework versions offer better collections.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf