Thursday, October 18, 2012

ArrayList



 srinivas.gavidi@gmail.com

Gavidi Srinivas   08886174458 09393087430



C# ArrayList

Array elements
ArrayList resizes dynamically. As elements are added, it grows in capacity to accommodate them. It is most often used in older C# programs. It stores a collection of elements of type object. This makes casting necessary.

Add elements

The Add method on ArrayList is used in almost every program. It appends a new element object to the very end of the ArrayList. You can keep adding elements to your collection until memory runs out. The objects are stored in the managed heap.
Program that uses ArrayList [C#]

using System.Collections;

class Program
{
    static void Main()
    {
 //
 // Create an ArrayList and add three elements.
 //
 ArrayList list = new ArrayList();
 list.Add("One");
 list.Add("Two");
 list.Add("Three");
    }
}

Result
    An ArrayList with three elements is created.
First, this is a complete console program that you can run in the Visual Studio IDE. When you run this example, there will be three elements added to the ArrayList. The first element is a string containing "One". The last element is "Three".
String Literal

Arguments

Structural programming with ArrayList is easy, as you can simply pass the object with the ArrayList type. However, in the receiving function, you have to know (or find out) what the type of each element is. Here we pass the ArrayList as an argument.
Program that uses ArrayList parameter [C#]

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
Return keyword
ArrayList as return value. You can also use the ArrayList as a return value. Use the ArrayList type as the return keyword at the start of your method.
Generally:It is best to reuse the same ArrayList instead of combining more than one.

Combine

There are different ways to add one ArrayList to another, but the best way is using AddRange. Internally, AddRange uses the Array.Copy or CopyTo methods, which have better performance than some loops.
Program that uses Add and AddRange [C#]

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
The first ArrayList has two elements added to it. Next, the second ArrayList has two elements added to it. The second ArrayList is then appended to the first using the AddRange method. The example finally shows the output.
Array.Copy MethodConsole.WriteLine

Count and Clear

The ArrayList class provides the Count property, which 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. The example also shows Clear.
Program that uses Count [C#]

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
Int keyword
The Count property returns an int, and you can assume this will always be a positive value. Sometimes, you can store the count in a local variable for better performance, but this isn't usually needed because no calculation takes place in the property itself.
Int Type
Clear. You can call the instance method Clear on your ArrayList. Internally, this calls the Array.Clear method. Sometimes, your code is clearer if you create a new ArrayList instead.
Array.Clear Method, Zero Out Array

Sort and reverse

Sorted letters: A through Z
Many dynamic arrays such as ArrayList must be sorted frequently, before insertion into the output web page or Windows program. This greatly improves the functionality and usability in programs. You can call the instance Sort method on an ArrayList, and then we call Reverse on that sorted collection. These methods work in-place.
Tip:You can sort subsets (ranges) of elements in your ArrayList using the third overload. This can be useful for rare situations, but isn't likely to be needed.
Additionally:You can Reverse only a range of your ArrayList.
Program icon
Sorting an ArrayList is done in many programs that use ArrayLists. Sorting provides a view of the data that is helpful for both users and computers. The Sort method in the base class libraries is a parameterless instance method on ArrayList.
Elements:It works on different element types—the example here shows strings.
Program that sorts ArrayList and reverses [C#]

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
Main method
The above console program defines the Main entry point, and in Main an ArrayList is declared and populated with several strings. The Sort method is then called. Its results are displayed next.
Finally:The collection is reversed. You can see the foreach loops on ArrayList here as well.
Framework: NET
Inside the base class libraries, you can see that the Sort method here always ends up in an internal TrySZSort or QuickSort method when it doesn't throw an exception. The TrySZSort internal method is optimized for one-dimensional arrays, also known as "Zero" arrays or vectors.
Performance of Sort. Because the TrySZSort method used in the base class libraries is implemented in native code, it has been heavily optimized.
Therefore:This method is likely faster than any solution written in the C# language.
In other words:Using Sort on ArrayList or on Array is faster than most custom implementations.

Insert and remove

Next we see how you can insert and remove elements with the Insert and Remove family of methods. Specifically, we see the RemoveAt method for erasing a single element, then the Insert method and RemoveRange methods.
Program that uses Insert and Remove [C#]

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 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 with for

For loop
In C# programming, the for loop is a very popular and useful loop construct. However, when using for on an ArrayList, you will need to cast the element after using its index. The [i] part in the example below demonstrates how to use the indexer on the ArrayList.
Indexer Examples
Program that uses ArrayList and for [C#]

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 with for.
 //
 for (int i = 0; i < list.Count; i++)
 {
     string value = list[i] as string;
     Console.WriteLine(value);
 }
    }
}

Output

man
woman
plant
As keyword
The "as" cast in C# is probably the best way to cast reference types such as string. After you cast, you can check the result for null before using the variable, to see if the cast succeeded.
As Cast Example
But:This is not always needed.

Get range

Another interesting method you can use is the GetRange method, which will return to you 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.
Program that uses GetRange [C#]

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
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.

IndexOf and LastIndexOf

Programming tip
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. IndexOf will return -1 if the element could not be located.
IndexOf String Examples

Convert to array

Arrays in C# offer more performance and compatibility, so you will want to convert ArrayLists to arrays. Due to the boxing and unboxing requirements with the ArrayList, you need to specify more complex casts than with the List constructed type.
Convert ArrayList to Array

BinarySearch

The BinarySearch method on ArrayList implements the binary searching algorithm. This uses a "divide and conquer" approach to finding the correct element, and only works on a pre-sorted array.
BinarySearch List
For this reason:Never use BinarySearch if your ArrayList might not be sorted.

Performance

Performance optimization
There is a significant performance penalty in using ArrayList, particularly on value types. This is because boxing occurs, which is a way the runtime turns a value type into an object. This site has some material on the cost of unboxing.
Unboxing Test

Should I use List?

Question and answer
Yes—assuming the project you are working on is compatible. Older applications may be using ArrayList, and it is often best not to have to rewrite them. Lists not only avoid boxing or unboxing, but they also lead to clearer and less bug-prone code.
List Examples
Note:With List, the compiler can check your code for type integrity before runtime.

Summary

The C# programming language
We saw how you can use ArrayList in a variety of contexts in the C# language. Generally, ArrayList is best used in legacy programs. The newer .NET Framework versions offer better collections in System.Collections.Generic.
However:The examples here are practical if you are working with an old program.
C#: Collections

No comments:

Post a Comment