Collections are an important concept in C# programming. There are many important collection classes in the System.Collections namespace such as ArrayList, Hashtable, SortedList, Stack, Queue etc. These classes are used as different types of data structures. These different types of classes have been developed in .NET keeping in mind the different requirements.
The general meaning of a collection is a collection of objects. These different items within the collection can be similar or dissimilar. Array is a collection of similar types of elements while ArrayList is a collection of dissimilar types of elements.
Array is a collection in .NET's System namespace, in which all elements are of same datatype. So Array is a type safe data structure but one of its limitations is that it can store only a predetermined number of elements. This means that once the size of the array is initially determined, its size cannot be increased or decreased.
Although its size can be changed using the Resize method with Array, but by doing this, a new Array object is created which copies the data of the old Array into this new Array.
The example of Array is explained in the following code.
using System;
namespace ArrayClass
{
class Program
{
static void Main(string[] args)
{
// array is created using new keyword
// array size must be given or array must be initialized
int[] arrInt = new int[4];
Console.WriteLine("Array size is {0}", arrInt.Length);
//auto initialized
Console.WriteLine("\n-----------------------");
Console.WriteLine("Auto initialized value at 0 index is {0}", arrInt[0]);
Console.WriteLine("Auto initialized value at 1 index is {0}", arrInt[1]);
Console.WriteLine("Auto initialized value at 2 index is {0}", arrInt[2]);
Console.WriteLine("Auto initialized value at 3 index is {0}", arrInt[3]);
//re-initialize
arrInt[0] = 11;
arrInt[1] = 21;
arrInt[2] = 13;
arrInt[3] = 14;
Console.WriteLine("\n-----------------------");
Console.WriteLine("Reinitialized value at 0 index is {0}", arrInt[0]);
Console.WriteLine("Reinitialized value at 1 index is {0}", arrInt[1]);
Console.WriteLine("Reinitialized value at 2 index is {0}", arrInt[2]);
Console.WriteLine("Reinitialized value at 3 index is {0}", arrInt[3]);
//resize array using Array.Resize() method
Array.Resize(ref arrInt, 6);
Console.WriteLine("\n-----------------------");
Console.WriteLine("After resize, value at 0 index is {0}", arrInt[0]);
Console.WriteLine("After resize, value at 1 index is {0}", arrInt[1]);
Console.WriteLine("After resize, value at 2 index is {0}", arrInt[2]);
Console.WriteLine("After resize, value at 3 index is {0}", arrInt[3]);
Console.WriteLine("After resize, value at 0 index is {0}", arrInt[4]);
Console.WriteLine("After resize, value at 1 index is {0}", arrInt[5]);
Console.WriteLine("\n-----------------------");
//sort array using Array.Sort() method
Array.Sort(arrInt);
for (int i = 0; i < arrInt.Length; i++)
{
Console.WriteLine("After sorting, value at {0} index is {1}" , i, arrInt[i]);
}
Console.WriteLine("\n-----------------------");
// array size not given but array initialized
string[] cities = new string[] { "Delhi", "Agra", "Patna", "Bhopal"};
foreach (string city in cities)
{
Console.WriteLine(city);
}
Console.WriteLine("\n-----------------------");
// array size not given but array initialized without new keyword
string[] continents = { "Asia", "Europe", "Africa", "Australia" };
foreach (string continent in continents)
{
Console.WriteLine(continent);
}
Console.WriteLine("\n-----------------------");
//copy array into another array
string[] continents2 = new string[5];
Array.Copy(continents, continents2, continents.Length);
continents2[4] = "America";
foreach (var cont in continents2)
{
Console.WriteLine(cont);
}
// convert array datatype using Array.ConvertAll method
float[] numbers = new float[5];
numbers[0] = 1.43f;
numbers[1] = 2.75f;
numbers[2] = 4.70f;
numbers[3] = 8.80f;
numbers[4] = 7.50f;
double[] dblNumbers = Array.ConvertAll(numbers, new Converter( n=>Convert.ToDouble(n)));
Console.WriteLine("\n-----------------------");
Console.WriteLine("Float to Double conversion:\n");
for (int i = 0; i < dblNumbers.Length; i++)
{
Console.WriteLine(numbers[i] +" => "+ dblNumbers[i]);
}
Console.ReadKey();
}
}
}
Cinema hall vs Website
Therefore, while Array provides type safety on one hand, on the other hand it does not give the flexibility to change the size. If the requirement of the business is such that the size of the data does not have to be changed, then you can use Array. For example the number of seats in a cinema hall. After the construction of the cinema hall, number of seats in the audience hall is fixed. Use of Array is desirable for such case. In contrast, the number of user members of a website cannot be fixed. Initially the number of members may be 30-40 but with time its number may increase immensely. So Array is not desirable in such situation.
ArrayList as Collection or Data Structure
Keeping in mind the limitation of Array, a class named ArrayList has been created inside the System.Collections namespace. The merit of this .NET ready-made class is that in this case, the number of elements in the ArrayList class can be increased or decreased according to the requirement.
While Array is typesafe, ArrayList is not typesafe. All the elements in Array have the same data type but elements of ArrayList can be of different datatypes.
using System;
using System.Collections;
namespace ProjectArrayList
{
class Program
{
static void Main(string[] args)
{
ArrayList Employee = new ArrayList();
//ArrayList accepts all types of data because it adds Object type data
Employee.Add("Amit");
Employee.Add(30);
Employee.Add("HR");
Employee.Add(40000);
//list ArrayList Employee data
foreach (var data in Employee)
{
Console.WriteLine(data);
}
//Object Initializer to add items in one step
Console.WriteLine();
ArrayList Product = new ArrayList() { "Mobile", 200000, "Black", "Samsung", "J7-Prime" };
//accessing ArrayList object using index
for (int i = 0; i < Product.Count; i++)
{
Console.WriteLine(Product[i]);
}
//There are several methods of ArrayList to add items, to remove items in several ways
//Create an ArrayList object called Student
Console.WriteLine();
ArrayList Student = new ArrayList() { 1, "Anand", "MCA", "Semester5", true, 20000 };
//add item at the end of the Student items
Student.Add("Agra");
//insert at a specified index postion
Student.Insert(2, "Gupta");
foreach (var item in Student)
{
Console.WriteLine(item);
}
Console.WriteLine();
//remove an item
Student.Remove("Semester5");
//remove an item at index position
Student.RemoveAt(2);
foreach (var item in Student)
{
Console.WriteLine(item);
}
Console.WriteLine("Total items in Student ArrayList object: {0}", Student.Count);
Console.WriteLine("Total Capacity of Student ArrayList object: {0}", Student.Capacity);
Console.WriteLine("BCA item exists or not: {0}",Student.Contains("BCA"));
Console.ReadKey();
}
}
}
Index vs Key
In the above example, we have seen some important properties and methods of ArrayList. Like Array, the elements of ArrayList are selected on the basis of index. This can sometimes cause problems. Suppose the number of members under the ArrayList is very high, then in such a situation, to access a particular member, its index number will have to be seen. Sometimes it may happen that its index number will be wrongly entered by the programmer and in such case programming error will occur in the code. This problem is also with Array because Arrays are also based on index. To avoid this situation, it is desirable to use key instead of index. The key is used to access a member within a Hashtable collection. Hashtable is in the System.Collections namnamespace like ArrayList.
using System;
using System.Collections;
namespace ProjectHashtable
{
class Program
{
static void Main(string[] args)
{
Hashtable Laptop = new Hashtable();
Laptop.Add("Acer", "20000,Black");
Laptop.Add("HP", "30000,White");
Laptop.Add("Asus", "45000,Silver");
Laptop.Add("Apple", "60000,Gold");
foreach (var value in Laptop.Values)
{
Console.WriteLine(value);
}
foreach (var key in Laptop.Keys)
{
Console.WriteLine(key);
}
Console.WriteLine(Laptop.ContainsKey("acer"));
Console.WriteLine(Laptop.ContainsKey("Acer"));
Console.WriteLine(Laptop.ContainsValue("60000"));
Console.WriteLine(Laptop.ContainsValue("60000,Gold"));
Console.WriteLine("Count Items in Laptop: {0}",Laptop.Count);
//does not throw exception if key is not found
Laptop.Remove("HP");
Laptop.Clear();
Console.WriteLine("Count Items in Laptop: {0}",Laptop.Count);
Console.ReadLine();
}
}
}
Edited on 5th July 2023
No comments:
Post a Comment