Forums » .NET » .NET »

array and array list


Posted Date: 18 Sep 2006      Posted By:: sasikala Profile photo    Member Level: Bronze    Member Rank: 0     Points: 2   Responses: 7



wht is the difference between array and arraylist



Responses

#78218    Author: vishal sharma      Member Level: Gold      Member Rank: 0     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

an arraylist is an array with undefined size.

 
#78221    Author: nidheesh      Member Level: Gold      Member Rank: 403     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

plz go thru

http://www.dotnetspider.com/qa/Question29774.aspx


 
#78276    Author: kaushik      Member Level: Gold      Member Rank: 890     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

An ArrayList enables you to store lists of objects (any type of object, even other ArrayLists). Using an ArrayList is similar to using an array, except that an ArrayList does not have any fixed upper bound. An ArrayList also has a number of useful properties and functions that it does not share with an array.

You can create a new ArrayList by using the following statement:



colArrayList = New ArrayList()

This statement creates an ArrayList that can initially store 16 objects. If you attempt to store more than 16 objects, the capacity of the ArrayList is automatically doubled. The capacity keeps doubling to handle the number of elements added.

If you know the number of elements that an ArrayList will store before you create the ArrayList, you can get the (ever so slight) performance benefit by declaring the ArrayList with a particular starting capacity. For example, if you know that an ArrayList will be used to store 100 items, you can declare it like this:



colArrayList = New ArrayList( 100 )

This ArrayList is declared to handle 100 elements. If you add a 101st element, the capacity of the ArrayList automatically doubles to 200.

You can determine the number of elements in an ArrayList at any time by using the Count property. You can determine the current capacity of an ArrayList at any time by using the Capacity property. For example, the following statements display the numbers 0 and 16:



Dim colArrayList As ArrayList

colArrayList = New ArrayList
Response.Write( colArrayList.Count & "," & colArrayList.Capacity )

The numbers 0 and 16 are displayed because they are the initial values of the Count and Capacity properties.

If you are working with a really huge ArrayList, you can trim its capacity back to its current size by using the TrimToSize method as follows:



colArrayList.TrimToSize()

The TrimToSize method changes the capacity of the ArrayList to match its current number of items.

Finally, if you want to clear all the objects out of an ArrayList and start over again, you can use the Clear method like this:



colArrayList.Clear()

The Clear method gets rid of all the current items in an ArrayList. However, it does not reset the capacity. To clear all the items and reset the capacity, you must call both the Clear and TrimToSize methods.

Adding Items to an ArrayList
You can add individual items to an ArrayList by using the Add method. For example, the following statement adds the string "Hello World!" to an ArrayList:



colArrayList.Add( "Hello World!" )

Remember that an ArrayList can contain any type of object. So, you can add integers, TextBox controls, or any weird object that you discover in the .NET framework.

When you add an object to an ArrayList, it's added to the end as the last element. You can return the index of an item that you add to an ArrayList like this:



intItemIndex = colArrayList.Add( "Hello World!" )

If this were the first item added to the ArrayList, intItemIndex would return 0; if it were the second, intItemIndex would return 1; and so on.

If you need to add multiple objects to an ArrayList at once, you can use the AddRange method. For example, the following statement adds all the items in an ArrayList named colAnotherArrayList to an ArrayList named colArrayList:



colArrayList.AddRange( colAnotherArrayList )

You also can add multiple duplicate items to an ArrayList by using the Repeat method:



colArrayList = ArrayList.Repeat( "Hello World!", 100 )

The Repeat method returns an ArrayList that contains a value repeated a certain number of times. In this case, the ArrayList would contain 100 items with the value "Hello World!".

If you need to insert an object into an ArrayList at a particular position, you can use the Insert method. For example, the following statement inserts the string "Hello World!" at the fourth index position:



colArrayList.Insert( 4, "Hello World!" )

The InsertRange method also corresponds to the AddRange method. You can use the InsertRange method, as shown here, to add multiple objects starting at a certain position:



colArrayList.InsertRange( 4, colAnotherArrayList )

This statement adds the contents of an ArrayList named colAnotherArrayList to an ArrayList named colArrayList starting at the fourth index position.

NOTE

You can use the AddRange and InsertRange methods to add other types of objects to an ArrayList as well. You can use these methods with any object that supports the ICollection interface.



You might be disappointed that you can add only single items to an ArrayList. The Add method accepts only one argument. However, this disappointment is not warranted. Remember that an ArrayList can contain any type of object. If you want to add multiple items to an ArrayList at a time, use a class with the ArrayList.

The page in Listing 24.1, for example, contains a class named Products. This class has both ProductName and Price properties.

Listing 24.1 MultiArrayList.aspx
<Script Runat="Server">

Public Class Product
Public ProductName As String
Public Price As Decimal

Public Sub New( ProductName As String, Price As Decimal )
MyBase.New()
Me.ProductName = ProductName
Me.Price = Price
End Sub
End Class

Sub Page_Load
Dim colArrayList As ArrayList

colArrayList = New ArrayList
colArrayList.Add( New Product( "eggs", 2.10 ) )
colArrayList.Add( New Product( "milk", 3.24 ) )

dlstDataList.DataSource = colArrayList
dlstDataList.DataBind()
End Sub
</Script>

<html>
<head><title>MultiArrayList.aspx</title></head>
<body>

<asp:DataList
ID="dlstDataList"
Runat="Server">
<itemTemplate>
<%# Container.DataItem.ProductName %>
- <%# String.Format( "{0:c}", Container.DataItem.Price ) %>
</itemTemplate>
</asp:DataList>

</body>
</html>

The C# version of this code can be found on the CD-ROM.

In the Page_Load subroutine in Listing 24.1, an ArrayList named colArrayList is declared. Two instances of the Product class are added to the ArrayList. Finally, the ArrayList is bound to a DataList control, and the two products are displayed.

Removing Items from an ArrayList
The most straightforward method of removing an item from an ArrayList is to use the Remove method. For example, the following statement removes the item "Hello World!" from an ArrayList:



colArrayList.Remove( "Hello World!" )

If an ArrayList contains duplicate items, the first item is removed. Beware that the Remove method performs an exact comparison, so it is case sensitive. If you attempt to remove a nonexistent item, nothing horrible happens. The whole ArrayList is searched for the item, and the Remove method gives up without generating an error.

If you need to remove an ArrayList item with a certain index, you can use the RemoveAt method like this:



colArrayList.RemoveAt( 4 )

This statement removes the item with an index of 4. If the ArrayList doesn't contain an item at index position 4, an error is generated.

If you want to remove a range of items in an ArrayList, use the RemoveRange method. For example, the following statement removes three items (items 2 through 4), starting at index position 2:



colArrayList.RemoveRange( 2, 3 )

Finally, if you want to clear all the items from an ArrayList, use the Clear method like this:



colArrayList.Clear()

Remember to call the TrimToSize method after calling Clear if you want to reduce the capacity of the ArrayList to the minimum (16 items).

Iterating Through the Items in an ArrayList
If you need to loop through the contents of an ArrayList, displaying each item, you can use either a For...Each or For...Next loop.

The following For...Each loop, for example, displays all the elements in an ArrayList named colArrayList:



Dim strItem As String

For Each strItem in colArrayList
Response.Write( strItem )
Next

You can do the same thing with a For...Next loop:



Dim intCounter As Integer

for intCounter = 0 To colArrayList.Count - 1
Response.Write( colArrayList( intCounter ) )
Next

In both cases, you assume that the ArrayList contains strings. If the ArrayList contains items with different types of data or you are not sure about the type of data contained in the ArrayList, you can loop through it by using an Object variable like this:



Dim objItem As Object

For Each objItem in colArrayList
Response.Write( objItem.ToString )
Next

An Object type can accept any type of value. So, regardless of whether an ArrayList contains integers, strings, classes, or whatever, you can assign the items to an Object type.

Sorting Items in an ArrayList
You can sort the items in an ArrayList by using the Sort method. For example, the page in Listing 24.2 sorts all the elements in an ArrayList named colShoppingList.

Listing 24.2 SortArrayList.aspx
<%
Dim colShoppingList As ArrayList
Dim strItem As String

colShoppingList = New ArrayList
colShoppingList.Add( "eggs" )
colShoppingList.Add( "milk" )
colShoppingList.Add( "beer" )

colShoppingList.Sort

For Each strItem in colShoppingList
Response.Write( "<li>" & strItem )
Next
%>

The C# version of this code can be found on the CD-ROM.

In Listing 24.2, three items are added to the ArrayList: eggs, milk, and beer. When the Sort method is called, the items are sorted in alphabetical order: beer, eggs, milk.

You reverse the order in which items in an ArrayList are sorted by calling the Reverse method. This method reverses the order of all the elements in an ArrayList. For example, the page in Listing 24.3 sorts a list of random numbers and reverses the results.

Listing 24.3 ReverseArrayList.aspx
<%
Dim colArrayList As ArrayList
Dim objRanNumber As Random
Dim intCounter As Integer
Dim intItem As Integer

colArrayList = New ArrayList
objRanNumber = New Random
For intCounter = 1 to 10
colArrayList.Add( objRanNumber.Next( 100 ) )
Next

colArrayList.Sort
colArrayList.Reverse

For Each intItem in colArrayList
Response.Write( "<li>" & intItem.ToString() )
Next
%>

The C# version of this code can be found on the CD-ROM.

Ten random numbers are assigned to the ArrayList in this listing. Next, the ArrayList is sorted, and the elements are reversed by calling the Reverse method.

Searching for Items in an ArrayList
You could find an element in an ArrayList by looping through all its elements until a match is found. However, this is a notoriously slow search algorithm. If an ArrayList contains thousands of elements, then, potentially, thousands of elements must be checked before a match is found.

You can perform this type of slow, linear search on an ArrayList by using the Contains method. For example, the page in Listing 24.4 uses the Contains method to find the number 53 in an ArrayList.

Listing 24.4 ContainsArrayList.aspx
<%
Dim colArrayList As ArrayList
Dim intCounter As Integer
Dim objRanNumber As Random

colArrayList = New ArrayList
objRanNumber = New Random
For intCounter = 1 to 1000
colArrayList.Add( objRanNumber.Next( 1000 ) )
Next

If colArrayList.Contains( 53 ) Then
Response.Write( "Found 53!" )
Else
Response.Write( "Couldn't Find 53!" )
End If
%>

The C# version of this code can be found on the CD-ROM.

In Listing 24.4, 1,000 random numbers are added to the ArrayList. The Contains method determines whether the number 53 is contained in it.

Using the Contains method can be slow when you're working with large ArrayLists. Fortunately, an ArrayList supports binary searches.

If you want to perform a binary search, the ArrayList must be sorted. A binary search takes advantage of the fact that the elements in an array occur in a certain order so that a match can be found more quickly.

CAUTION

A binary search can return incorrect results if an ArrayList is not sorted.



The page in Listing 24.5 illustrates how you can use the BinarySearch method.

Listing 24.5 BinarySearchArrayList.aspx
<%
Dim colArrayList As ArrayList
Dim objranNumber As Random
Dim intCounter As Integer
Dim intItemIndex As Integer

colArrayList = New ArrayList
objRanNumber = New Random
For intCounter = 1 to 1000
colArrayList.Add( objRanNumber.Next( 1000 ) )
Next

colArrayList.Sort()

intItemIndex = colArrayList.BinarySearch( 53 )
If intItemIndex > 0 Then
Response.Write( "Found 53!" )
Else
Response.Write( "Couldn't Find 53!" )
End If
%>

The C# version of this code can be found on the CD-ROM.

If the BinarySearch method finds a match, it returns the index of the matched item in the ArrayList. Otherwise, it returns a negative number.

By default, the BinarySearch method performs a case-sensitive search. If you need to perform a search that is not case sensitive, call the BinarySearch method like this:



intItemIndex = colArrayList.BinarySearch( "Smith", New CaseInsensitiveComparer )

This statement performs a binary search for Smith using an instance of CaseInsensitiveComparer. So, the statement matches both Smith and smith.

fell free mail me on kaushikb2005@yahoo.co.in





 
#78401    Author: Sidhartha Gundavarapu      Member Level: Gold      Member Rank: 0     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

array as the name suggests is a sequential array of elements, whereas arraylist is list based. array bounds are fixed and arraylist bound is dynamic. the advantages of an array is that you can have multi-dimensions and jagged arrays, whereas the only way to achieve this in arraylist is to have an arraylist of type object and performance impact is very high.

 
#78402    Author: Sidhartha Gundavarapu      Member Level: Gold      Member Rank: 0     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

array as the name suggests is a sequential array of elements, whereas arraylist is list based. array bounds are fixed and arraylist bound is dynamic. the advantages of an array is that you can have multi-dimensions and jagged arrays, whereas the only way to achieve this in arraylist is to have an arraylist of type object and performance impact is very high.

 
#78404    Author: Sidhartha Gundavarapu      Member Level: Gold      Member Rank: 0     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

array as the name suggests is a sequential array of elements, whereas arraylist is list based. array bounds are fixed and arraylist bound is dynamic. the advantages of an array is that you can have multi-dimensions and jagged arrays, whereas the only way to achieve this in arraylist is to have an arraylist of type object and performance impact is very high.

 
#78405    Author: Sidhartha Gundavarapu      Member Level: Gold      Member Rank: 0     Date: 18/Sep/2006   Rating: 2 out of 52 out of 5     Points: 2

*Sorry* for the spam here.. I'm using the answering machine and when I tried to submit, it was giving operation timed out

 
Post Reply

 This thread is locked for new responses. Please post your comments and questions as a separate thread.
If required, refer to the URL of this page in your new post.



Next : loosing Collection properties when I am Closing MS Visual Studio IDE
Previous : textbox
Return to Discussion Forum
Post New Message
Category: .NET

Related Messages

Subscribe to Subscribers
Active Members
TodayLast 7 Daysmore...

Awards & Gifts
Talk to Webmaster Tony John

Online Members

More...
Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India