Objective of the Module
- Introduction
- ArrayList
- Hashtable
- BitArray
Introduction
.NET offers a variety of collections, such as ArrayList, Hashtable, Queues and Dictionaries. Collections are abstractions of data algorithms. An ArrayList abstracts a dynamic array, a Hashtable collection abstracts a lookup table, a Queues collection abstracts queues and so on. In addition, collections implement the ICollection, IEnumerable and IClonable interfaces. The detailed specification for each collection is found under the System.Collection namespace.
ArraysList Collection
An ArrayList is a dynamic array and implements the IList interface. Each element is accessible using the indexing operator. Whereas the traditional array has a fixed number of elements, ArrayList elements can be added or removed at run time.
We can an object from the ArrayList using a general type of syntax as follows:
- ArrayList obj = new ArrayList();
Here you can use the new keyword to create an instance of the ArrayList object. You don't need to specify the size. Once you have an empty ArrayList object, you can use the Add() method to add elements to it as in the following:
- obj.Add(“item1”);
- obj.Add(“2”);
- obj.Add(“Delhi”);
Each new item in the ArrayList is added to the end of the list, so it has the largest index number. If you wanted to add an item to the middle of the list, then you can use Insert() with a numeric argument as follows:
You can also remove members of the ArrayList using either Remove() or RemoveAt() methods as in the following.
- Obj.Remove(“item1”);
- Obj.RemoveAt(3);
Benefits of ArrayLists
- Insert Elements: An ArrayList starts with a collection containing no elements. You can add them in any position as you choose them.
- Automatic Resizing: you do not need to specify the array size; as you add elements, the array automatically ensures there is enough of the array.
- Flexibility when Removing elements: you can remove any elements from an Arraylist very easily.
Limitations of ArrayLists
The flexibility of an ArrayList comes at the cost of performance. Since memory allocation is very expensive, the fixed number of elements of the simple array makes it much faster to work with.
Note: an ArrayList is slower and more resource-intensive than a conventional array.
Simple ArrayList Example
The following example shows an array list with an undefined size. Elements are adding dynamically depending on the requirements. We are adding elements via the Add() method as well as using the Insert() method at a specific location. Later we are displaying all the elements by iterating using a for loop.
- using System;
- using System.Collections;
-
- namespace CollectionApp
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- ArrayList obj = new ArrayList();
-
-
- obj.Add("India");
- obj.Add("USA");
- obj.Add("Russia");
- obj.Add("300");
-
-
- obj.Insert(2, "Japan");
-
-
- for (int i = 0; i < obj.Count;i++ )
- {
- Console.WriteLine("At Index["+i+"]= "+obj[i].ToString());
- }
-
- Console.WriteLine("_________________");
- Console.WriteLine("Press any key");
- Console.ReadKey();
- }
- }
- }
After build-up and the running of this program, the output of the following program is as in the following:
![Array List]()
Figure 1.1 – Array List
Hashtables
In some respects, Hashtable objects are quite similar to an ArrayList object except they are not required to use a numerical index. Instead, we can use a text key that can be numeric.
You can create a Hashtable object using the same syntax as an ArrayList as in the following:
- Hashtable obj = new Hashtable();
Once it is created, you need to specify the key/value pairs. Remember that the key is like an index for the entry and the value is the data we are storing. We store each elements using the Add() method with the following syntax as in the following:
- Obj[“in”] = “india”;
- Obj[“en”] = “England”;
- Obj[“us”] = “USA”;
A Hash table with numbers or dates for the keys are written as in the following:
- Obj[Convert.ToDateTime(“21/12/2012”)] = “The Judgment day”;
Note: you need to convert DateTime index values when they are used as an index for a Hashtable.
To read elements, you just need to specify the key and value is returned. The following code puts the value “india” into a variable named Country.
- string Country = Convert.ToString(obj[“in”]);
Benefits of Hashtable
- Insert Elements: You can add as many pairs of key/value elements as required. You do not need to specify the size ahead of time.
- Non-numeric index: You can use text, number and dates as your key (index).
- Faster Lookup: The hashtable collection caters very fast lookup of elements.
- Flexibility when Removing elements: you can remove any elements from an Arraylist very easily.
Limitations of ArrayLists
- Key must be unique: Hashtables have a key uniqueness requirement that is very cumbersome to manipulate.
- No useful sorting: Sorting is not done using keys or values. Items in a Hashtable are sorted internally to make it easy to find objects very quickly.
- Performance: Although the lookup is very quick in a Hashtable the CLR must do much work to keep its mechanism that is very resource-intensive.
Simple Hashtable Example
The following Hashtable program manipulates with a date index. First we define a Hashtable object and add some predefined dates to the object. Thereafter we create a DateTime type variable to store user input and finally we display the output.
- using System;
- using System.Collections;
-
- namespace CollectionApp
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- Hashtable obj = new Hashtable();
-
-
- obj[Convert.ToDateTime("02/14/2012")] = "Valentine day";
- obj[Convert.ToDateTime("12/22/2012")] = "Math day";
- obj[Convert.ToDateTime("08/15/1947")] = "Independence day";
-
-
- Console.WriteLine("Enter date 'Month/Date/Year' Format");
- DateTime DateData = DateTime.Parse(Console.ReadLine());
-
-
- Console.WriteLine(obj[DateData]);
-
- Console.WriteLine("_________________");
- Console.WriteLine("Press any key");
- Console.ReadKey();
- }
- }
- }
After successfully compiling the program mentioned previously, the output is as in the following:
![Hashtable]()
Figure 1.2: Hashtable
BitArray
Bit values are 1 and 0, where 1 represents true and 0 is false. A BitArray collection provides an efficient way to store and retrieve bit values. It allows us to perform bitwise operations as well as count the total number of bits. The contents of this collection are not Objects but Boolean values because BitArray can hold a large number of Boolean values called bits. One of most significant features of a BitArray is that they are resizable and that is useful if you don't know the number of bits needed in advance.
You can create a BitArray object using the same syntax as defined for other collections. A BitArray provides several constructors. Here we are defining 7 bits in length in the BitArray as in the following.
- BitArray obj = new BitArray(7);
Note: The static members of BitArray are thread-safe whereas instance members are not.
Simple BitArray Example
The following program shows BitArray manipulation. It creates a bit array with 16 bits, indexed from 0 to 15. The Count property calculates the total number of bits. The SetAll() method sets all the 16 bits to true. Then the Set() method changes the third bit to false. Instead of the Set method, you can also use an indexer.
- using System;
- using System.Collections;
-
- namespace CollectionApp
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- BitArray bobj = new BitArray(16);
-
-
- Console.WriteLine("Total bits="+bobj.Count);
-
- bobj.SetAll(true);
-
-
- bobj.Set(2, false);
-
-
- bobj[3] = false;
-
- DislayBits(bobj);
-
- Console.WriteLine("\n_________________");
- Console.WriteLine("Press any key");
- Console.ReadKey();
- }
-
- static void DislayBits(BitArray obj)
- {
- foreach(bool bits in obj)
- {
- if (bits)
- Console.Write(1);
- else
- Console.Write(0);
- }
- }
-
- }
- }
The following is a display of the results of the initialized and configured bits:
![Bit Array]()
Figure 1.3 – Bit Array
The BitArray collection implements the properties and methods of the ICollection interface. The following table shows the properties and methods of BitArray:
|
Members |
Descriptions |
Properties |
Count |
Contains the number of items currently in the bitarray |
IsReadOnly |
Contains True if the bitarray is read-only and False otherwise |
IsSynchronized |
Contains True if the bitarray is synchronized and False otherwise |
Item[] |
Contains an index of all the items in the bitarray |
Length |
Enables the developer to get and change the length of the bitarray |
Methods |
And() |
Performs the logical "And" operation on the bitarray |
Clone() |
Returns a copy of the bitarray |
CopyTo() |
Copies the bitarray to another type of collection |
Get() |
Returns the value of a specific location in the bitarray |
Not() |
Performs the logical "Not" operation on the bitarray |
Or() |
Performs the logical "Or" operation on the bitarray |
Set() |
Sets the value of a specific location in the bitarray |
SetAll() |
Sets all the values in the bitarray |