ArrayList.md - brainchildservices/curriculum GitHub Wiki
Slide 1
C# | ArrayList Class
It represents an ordered collection of an object that can be indexed individually.
It is basically an alternative to an array. However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself automatically.
It also allows dynamic memory allocation, adding, searching and sorting items in the list.
Slide 2
Difference between Array and ArrayList
Slide 3
How to create an ArrayList?
For using ArrayList we need to add the System.Collections namespace
For creating an ArrayList the new keyword is used to declare an object of ArrayList
Two ways to create an ArrayList:
-
Without specifying the capacity of the ArrayList
using System; using System.Collections; //1. Add the namespace public class Program { public static void Main() { ArrayList arrList = new ArrayList(); //2. Create the arraylist object using the new keyword } }
Slide 4
-
By specifying the capacity of the ArrayList
using System; using System.Collections; //1. Add the namespace public class Program { public static void Main() { ArrayList arrList = new ArrayList(5); //2. Create the arraylist object using the new keyword and specifying the capacity } }
Slide 5
How to Add elements to an ArrayList?
Elements can be added to the ArrayList using the ArrayList.Capacity property.
How to find the capacity an ArrayList?
The capacity property in ArrayList class gets or sets the number of elements that the ArrayList can contain.
- The capacity of an ArrayList can be found using the ArrayList.Capacity property.
If the capacity of the ArrayList is not specified at the time of the creation of the ArrayList and no elements are added to it, the capacity of the ArrayList would be 0.
https://dotnetfiddle.net/uINKBt
Slide 6
After adding one element to the array, the capacity is automatically increased to 4.
https://dotnetfiddle.net/JdNI49
Once the ArrayList is about to store the 5th element, the capacity is increased to 8
https://dotnetfiddle.net/0O5LsW
Once the ArrayList is about to store the 9th element, the capacity is increased to 16
https://dotnetfiddle.net/tYKHZo
Slide 7
Once the ArrayList is about to store the 17th element, the capacity is increased to 32 and so on....
For ArrayList whose capacity is initialized at the time of creation, the capacity increases in the order of the capacity specified at the stage of creation.
https://dotnetfiddle.net/CFpClR
How to count the number of elements in an ArrayList?
The number of elements in an array can be counted using the ArrayList.Count property.
Count: Gets the number of elements actually contained in the ArrayList.
https://dotnetfiddle.net/j4cfeW
Slide 8
What elements can be stored to an ArrayList?
ArrayList.Add property allows us to add any object to the ArrayList
https://dotnetfiddle.net/wJ5tN8
How to access/read elements in an ArrayList?
- ArrayList items are stored on an index basis. The first item stored is at index 0 whereas the next item stored at the next index, in other words, index 1 so you can also retrieve items from an ArrayList using an index.
https://dotnetfiddle.net/VXv71U
Slide 9
- We can iterate through the array using the for loop or the for each loop.
Using foreach loop:
https://dotnetfiddle.net/T12h9F
OR if we don't know the exact data type of all the elements, we can iterate through the array using an object reference
https://dotnetfiddle.net/NeaTfh
Using for loop:
https://dotnetfiddle.net/ir77yb
Slide 10
How to change an element of the ArrayList?
We can change the element at specific index using the [] operator just like we do with arrays.
https://dotnetfiddle.net/BmCr5C
However, if we try to change the value of an index which we haven't added to the ArrayList before, we would get System.ArgumentOutOfRangeException: Index was out of range exception.
https://dotnetfiddle.net/UjOJon
How to insert an Item to a C# ArrayList?
The Add method adds an item to the end of the ArrayList whereas Insert adds an item at a specific index position.
ArrayList.Insert(IndexWherethereElementIsToBeInserted, ValueOfTheElementToBeInserted);
https://dotnetfiddle.net/Mqi8GE
Slide 11
After the insert operation, the index of all the elements to the right of index where we inserted the element gets increased by 1.
How to remove an item from an ArrayList
You can remove an item or items from an ArrayList. The ArrayList class provides four methods to remove an item or items from it. These methods are:
- Remove
- RemoveAt
- RemoveRange
- Clear
Slide 12
-
Remove
The Remove() method has one parameter that is of object type. We need an pass that object to the Remove method which should be removed from the ArrayList. Remove(object)
https://dotnetfiddle.net/TAJhwy
The Remove() method removes only the first matching element that it encounters. So if there are duplicate elements, Remove() remove method removes only the first occurrence of the matching element.
https://dotnetfiddle.net/59gFSj -
RemoveAt
RemoveAt(index)
The RemoveAt method takes one parameter which is the index of the element to be removed.
https://dotnetfiddle.net/DBAtBa
Slide 13
-
RemoveRange
The Remove() method and the RemoveAt method can remove only one element at a time. If we want to removed more than one element, then we would need to call these more than once.
With the RemoveRange we get to select the start index and a count of the number of elements to be removed.
RemoveRange(StartIndex, CountofElementsToBeRemoved)
https://dotnetfiddle.net/OGLkUC -
Clear
The Clear method of ArrayList removes all the items from the ArrayList but doesn’t reduce the capacity of the ArrayList.
https://dotnetfiddle.net/t9l4Rc
Slide 14
Removing items from the ArrayList won't bring down the capacity of the ArrayList.
Performance of ArrayList
There is a performance penalty in the use of ArrayList, particularly on value types. This is because boxing occurs, which is a way the runtime turns a value type into an object. Each element or item is added as an object to an ArrayList.
Exercise:
- Create a list of strings, using the class ArrayList which already exists in the DotNet Platform.
Once created, show all the items stored in the list.
Insert one new item in the second place of the list and then show again all the items checking if the insertion was correct.
Adding User-Defined objects to ArrayList
Collection classes are used to store built in objects such as Integer, String, Character etc. But the potential of collection classes isn't just restricted to the storage of built-in objects. Collections classes can store any similar type of objects, be it objects of a built-in class or objects of an user-defined class. This feature of collection class is very userful when we are making an application which requires us to store many objects of user-defined classes and not just objects of built-in classes.
In this example, we are going to store a User-Defined class Student to the ArrayList.
The Student class has properties: Name, age and marks.
https://dotnetfiddle.net/WZhsgj
We create a Constructor for the Student class so that we pass values to the properties at the time of creation of Student objects.
https://dotnetfiddle.net/4XUvzK
In the Main method we create few instances of the Student class
https://dotnetfiddle.net/z5IGLW
Adding namespace System.Collections and creating an ArrayList, studArrList to store Student objects.
https://dotnetfiddle.net/GnQC8C
Next we will add the student objects to the studArrList ArrayList
https://dotnetfiddle.net/AGaUzH
Option1: By TypeCasting
Now the question is how can we print/access the objects we have added?
Can we use the [] and then the index to access the object?
https://dotnetfiddle.net/ExEPKx
But that gives us only the classname.
We access the members of the class using the dot operator(objectName.MemberName). Lets try that.
To make sure that we are trying to access the object, we would need to put the objectName in brackets.
But that gives us only the default methods(ToString, ) that we get only the default methods of an object like dump, equals, ToString() etc.
https://dotnetfiddle.net/hmAYOF
Lets take another example of an array with two integer elements stored to it. And we need to add these elements and store to a variable sum.
We get an error: Operator '+' cannot be applied to operands of type 'object' and 'object'.
https://dotnetfiddle.net/iDBmeq
Now if we need to add these elements we would need to explicitly type cast the elements into integers.
https://dotnetfiddle.net/3qvWrf
In the same way, we type casted the integer numbers to integer,the Student objects in the ArrayList needs to be type casted to Student type.
((ClassName)ArrayList[index]).Memebers
https://dotnetfiddle.net/0QWYTg
This process of type casting allows us to access the members of the class.
Now we can make a method GetData in Student Class with string return type in the Student class which uses the properties of the Class Student.
https://dotnetfiddle.net/lLMlzK
Using the typecasting operation we can call the GetData method in Main.
https://dotnetfiddle.net/E9Yt3B
Option1: Overriding the ToString() Method
When we put the dot operator after the ArrayList object name, we were getting the default ToString() method.
So we have another option to override the ToString() and make it return a string that we would like to get.
We are currently here:
https://dotnetfiddle.net/hmAYOF
We will write an override method for ToString in Student class.
https://dotnetfiddle.net/8UxC9I
Now without type casting the ArrayList object, we would be able to call the ToString Method in Main method. https://dotnetfiddle.net/xcmtTZ
Exercise2:
Create a C# program that uses a ArrayList to store a list of people. First prepare a class called Person.cs with two properties (name and age) and a ToString() method to print the result.
Then define a ArrayList and request the information (name and age) of three people from the user.
To end the program it prints the data of the people going through the list of data.
References:
https://www.youtube.com/watch?v=sqKcvVMz5AM
https://www.geeksforgeeks.org/how-to-create-the-arraylist-in-c-sharp/
https://www.tutorialspoint.com/What-is-the-Capacity-property-of-an-ArrayList-class-in-Chash
https://www.geeksforgeeks.org/c-sharp-arraylist-class/
https://www.tutorialspoint.com/csharp/csharp_arraylist.htm
https://www.c-sharpcorner.com/UploadFile/3d39b4/arraylist-in-C-Sharp/
https://practiceexercisecsharp.blogspot.com/2017/05/exercise-c-sharp-1105-arraylist.html
https://www.c-sharpcorner.com/UploadFile/a42a0c/why-how-to-override-tostring-method-in-C-Sharp/
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method
https://www.youtube.com/watch?v=n5s_hgjM7Qc
http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/AdduserdefinedobjecttoanArrayList.htm