Copying an array to an arraylist

janvdl

Newcomer
Joined
Feb 13, 2009
Messages
1
Location
South African Republic
Hello everyone :)

Well I'm busy with a homework assignment on copying 4 arrays each to a seperate arraylist.

The first array is of type int, the second string, then char, then decimal.

I tried using the CopyTo() method but then I get errors about the size of the arraylist or something, because I use the ToArray() method on the destination arraylist. So I decided to do it as follows:

Code:
ArrayList myArrayList = new (iArray);

And so I repeat that for all 4 the arrays.

---

But how would I have proceeded if i wanted to use the CopyTo() method? Must I declare a fixed size for the arraylist when using the ToArray() method? It won't really be very elegant programming. What are your opinions? :confused:
 
You didn't post this, but I suspect you have code that looks something like this (correct me if I'm wrong)

Code:
int[] myIntArray = {1,2,3,4};
ArrayList myIntArrayList = new ArrayList(myIntArray.Length);
myIntArray.CopyTo(myIntArrayList.ToArray());

This code will not work, because you cannot set the value of a method:

Code:
// this will never work
myObject.SomeMethod() = 245;

Now, depending on the version of .Net you are using, ArrayList may not be the best option. You may be better served with a List<T> or a Generic List.

If you are on Pre .Net v2.0 you'll need to use the ArrayList like this:

Code:
int[] myIntArray = {1,2,3,4};
ArrayList myIntArrayList = new ArrayList(myIntArray);

By passing in the the Array into the constructor of the ArrayList (one of the overloads accepts a collection) the ArrayList should pickup each value of the collection.

If you are using .Net v2.0 or later, you can use a Generic List, or a strongly typed list as follows:

Code:
int[] myIntArray = {1,2,3,4};
List<int> myIntList = new List<int>(myIntArray);

String[] myStringArray = {"1", "2", "3", "4"};
List<String> myIntList = new List<String>(myStringArray);

It is possible, and recommended to use your own storngly typed collections even in .Net 1.0/1.1 see this link for further information http://www.ondotnet.com/pub/a/dotnet/2003/03/10/collections.html

The advantage of the Generic List (or strongly typed list) is that you cannot mix object types that are in your list/collection.

HTH
 
If you need to add an array of items to a list after the list has been created, there is the ArrayList.AddRange() method (or List<T>.AddRange() method), which allows you to insert an entire array, list, or any other collection to the list.
 
Back
Top