1

i'm new to asp.net and i'm writing some code to learn about arraylist

al.Add((string)"asfsaf");
al[1] = "bcd";
al.TrimToSize();

Response.Write(al[1]);

from the above code, the line al[1] = "bcd"; is wrong, is arraylist support insert elements by index? if not, any other data structure can be replaced?

thanks

3 Answers 3

4

You can try .Insert() as below:

al.Insert(1, "bcd");
Sign up to request clarification or add additional context in comments.

1 Comment

This will fail if the list contains no element.
1

EDIT: You can't directly insert based on an index in a List, you can only Set(Modify)/Get a value to an index. If it exists


You can use indexing with an ArrayList as well, but use a Generic List instead of ArrayList. Its type safe. and Also support insertion based on index.

With ArrayList you can use the index

List<string> list = new List<string>();
list.Add("first element");
list.Add("2nd element");

Console.Write(list[0]);
Console.Write(list[1]);

list[0] = "AAA - element"; //In actual its a modification, 
                           //if there is no element, there will b exception
list[1] = "BBB - element";

Remember you can't directly set element of a list based on an index.

6 Comments

I wouldn't call it insertion based on index, but modification based on index.
@DaveDoknjas, I think you can't directly insert based on an index in a List, you can only Set/Get a value to an index. If it exists
if remove list.Add("first element"); list.Add("2nd element");, the script go wrong
That is because there are no items in the list if you remove Add statement. Thats what I said in the Edit, you can only modify/Get a value from the list based on the index, you can't insert using an index
@Habib - I know - that's why I called it modification based on index.
|
0

al[1] needs to be created before you can use it via the indexer.

al[1] = "bcd"; will result in an exception of ArgumentOutOfRangeException.

Remember array indexes start from zero.

If you want to overwrite it, it should be like this.

al[0] = "bcd";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.