0

I know this must be a duplicated question, but I had to ask because I can't understand why my code doesn't work. I get this error:

Index was out of range. Must be non-negative and less than the size of the collection

Here is the part of my code that throws an exception:

private static void getPattern(ArrayList arrayList1)
    {
        ArrayList array_2008 = new ArrayList();
        ArrayList array_2009 = new ArrayList();
        ArrayList array_2010 = new ArrayList();
        ArrayList array_2011 = new ArrayList();
        ArrayList array_2012 = new ArrayList();

        for (int i = 0; i < arrayList1.Count; i++)
        {
            if (arrayList1[i].ToString().Contains("2008"))
            {
                int a = getIndex(arrayList1[i].ToString());
                array_2008[a] = arrayList1[i];
            }
            if (arrayList1[i].ToString().Contains("2009"))
            {
                int a = getIndex(arrayList1[i].ToString());
                array_2009[a] = arrayList1[i]; 
            }
            else if (arrayList1[i].ToString().Contains("2010"))
            {
                int a = getIndex(arrayList1[i].ToString());
                array_2010[a] = arrayList1[i];
            }
            else if (arrayList1[i].ToString().Contains("2011"))
            {
                int a = getIndex(arrayList1[i].ToString());
                array_2011[a] = arrayList1[i];
            }
            else if (arrayList1[i].ToString().Contains("2012"))
            {
                int a = getIndex(arrayList1[i].ToString());
                array_2012[a] = arrayList1[i];
            }
        }

Please give me an answer. I don't know what am I supposed to do. It throws the exception above mentioned. Problem is that it throws at arraylist1[0] position. why is that? How to solve that?

here the values:

"4/28/2008","4/29/2008",5/10/2008 likewise 33 values

Mlarnt90
  • 176
  • 1
  • 4
  • 19
  • Please post the error so that it's possible to address question. – Phani Dec 04 '15 at 15:02
  • error is self describing that at that index does not exists in collection – Ehsan Sajjad Dec 04 '15 at 15:03
  • 7
    It is almost 2016. Stop using `ArrayList`. Use `List` instead. – Soner Gönül Dec 04 '15 at 15:04
  • How are you calling this method? Seems like `arraylist1` (terrible name for a function parameter by the way) is empty, i.e. not even `arraylist1[0]` exists. `ArrayList` reminds me of Java, together with the casing in `getPattern()` – Maximilian Gerhardt Dec 04 '15 at 15:06
  • 2
    Your `ArrayList`s (`array_2008`, `array_2009`, `array_2010`, `array_2011`, and `array_2012`) are empty so you cannot access indexes. You need to add something. – juharr Dec 04 '15 at 15:06
  • using List whould solve the problem? if yes then how? – Mlarnt90 Dec 04 '15 at 15:06
  • 1
    @MaximilianGerhardt Clearly the issue is not with `arraylist1` since the `for` loop is using `arraylist1.Count`. – juharr Dec 04 '15 at 15:09
  • @Mlarnt90 you should not ask such an obvious question, if you are not familiar with `List` Generics then you should honestly do a simple Google Search.. the `` in the list would be of type `int` hint `var someList = new List` also use the debugger and tell us what the contents of `arraylist1` are... – MethodMan Dec 04 '15 at 15:09
  • 1
    @Mlarnt90 No, using `List` would not solve your immediate problem, but it would be better to not have to do `arrayList[i].ToString()`. – juharr Dec 04 '15 at 15:10
  • 2
    By the way, [What is an “index out of range” exception, and how do I fix it?](http://stackoverflow.com/q/20940979/447156) – Soner Gönül Dec 04 '15 at 15:12
  • 4
    OP is a beginner, maybe it would be more helpful to walk them through their issue instead of berating them for not doing things exactly the way you would. – Cᴏʀʏ Dec 04 '15 at 15:13
  • 1
    it sure would be nice to see what the values are in the `arrayList1` – MethodMan Dec 04 '15 at 15:16
  • here the values: a =118, arrayList1 count =33, arrayList1[i] = "4/28/2008" – Mlarnt90 Dec 04 '15 at 15:21
  • put the values in your original question.. click the edit link under your original question – MethodMan Dec 04 '15 at 15:23
  • @Mlarnt90 you need to show at least 1 line of the contents of `arrayList1` don't show the output of the `indexed` – MethodMan Dec 04 '15 at 15:24
  • arrayList1[0] = "4/28/2008" – Mlarnt90 Dec 04 '15 at 15:28
  • you are not understanding.. do this.. set a breakpoint on the second line in the for loop and your mouse over `arrayList1` I don't care about `arrayList1[0]` I want to see a what values you have in `arrayList1` for example `"4/28/2008", "5/28/2009", "10/01/2008"` do you know how to use the quick watch..? / debugger – MethodMan Dec 04 '15 at 15:31
  • I added them on my original question.. – Mlarnt90 Dec 04 '15 at 15:35
  • the problem is can't assign `array_2008[a] = arrayList1[i];` the list has a `.Add()` method ..you need to assign it like this `array_2008.Add( arrayList1[i]);` – MethodMan Dec 04 '15 at 15:39
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/96997/discussion-between-methodman-and-mlarnt90). – MethodMan Dec 04 '15 at 15:47

5 Answers5

1
var array_2008 = new List<object>() {0, string.Empty};
var array_2009 = new List<object>() {0, string.Empty};
var array_2010 = new List<object>() {0, string.Empty};
var array_2011 = new List<object>() {0, string.Empty};
var array_2012 = new List<object>() {0, string.Empty};

for (int i = 0; i < arrayList1.Count; i++)
{
    var aIndex = getIndex(arrayList1[i].ToString());
    if (arrayList1[i].ToString().Contains("2008"))
    {
        //array_2008[0] = aIndex;
        //array_2008[1] = arrayList1[i]; uncomment this if you wanat to add List<T> other wise comment out bottom code 
        //and uncomment code above
        array_2008.Add( new List<object>()
        {
            aIndex, arrayList1[i].ToString() 
        });
    }
    if (arrayList1[i].ToString().Contains("2009"))
    {
        array_2009.Add( new List<object>()
        {
            aIndex, arrayList1[i].ToString() 
        });
    }
    else if (arrayList1[i].ToString().Contains("2010"))
    {
        array_2010.Add(new List<object>()
        {
            aIndex, arrayList1[i].ToString() 
        });
    }
    else if (arrayList1[i].ToString().Contains("2011"))
    {
        array_2011.Add(new List<object>()
        {
            aIndex, arrayList1[i].ToString() 
        });
    }
    else if (arrayList1[i].ToString().Contains("2012"))
    {
        array_2012.Add(new List<object>()
        {
            aIndex, arrayList1[i].ToString() 
        });
    }
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • @Mlarnt90 I would suggest switching the `ArrayList` over to `List` it's very easy to implement for example `var array_2008 = new List` since I don't know if you're loading strings, or dates if they are strings then change List to `List` – MethodMan Dec 04 '15 at 15:51
  • also you don't need this line `int a = getIndex(arrayList1[i].ToString());` if it contains the Value that you are looking for based on the position in the arrayList1 then you already know what Index position you are sitting at based on `i` in the loop – MethodMan Dec 04 '15 at 15:55
  • thanx a lot sir.I got the answer I wanted. Really appreciate your effort. – Mlarnt90 Dec 04 '15 at 17:34
  • Thank u all for your efforts...It really helped me... – Mlarnt90 Dec 04 '15 at 17:36
  • @Mlarnt90 no problem I figured after you showed me what you wanted the List values to look like I knew that you could utilize `List` cheers – MethodMan Dec 04 '15 at 17:59
0

You can simplify the method method even more by relying on the List<T> class and using FindAll() with a predicate.

private static void getPattern(List<string> inputData)
    {
      List<string> array_2011 = inputData.FindAll(data => data.Contains("2011"));
      //...
    }

You can change the generic argument of the List<T> to whatever is inside that ArrayList, but it's much easier to work with Linq in C# instead with ArrayList (seems like you've got that from Java?). You can even extend this to be compatible with any IEnumerable collection. For the general object case:

private static void getPattern(List<object> inputData)
    {
      List<object> array_2011 = inputData.FindAll(data => data.ToString().Contains("2011"));
      //...
    }

This will avoid having a collection of size 0 being iterated over.

Maximilian Gerhardt
  • 5,188
  • 3
  • 28
  • 61
  • You're assuming that the `ArrayList` contains `string`. For all we know it could be `DateTime` and the OP is checking what the year is. – juharr Dec 04 '15 at 15:12
  • @MaximilianGerhardt I doubt the OP known's about `Predicates` when the OP is asking in a comment how to use `List` – MethodMan Dec 04 '15 at 15:13
  • Woops, correct, he's just calling `.ToString()` on the thing inside the `arrayList1`. Then again, you could use an `List` and also use `.ToString()` on it, I just wanted to show him that these `for` loops are unnecessary with a small Linq query and better dataclasses. – Maximilian Gerhardt Dec 04 '15 at 15:15
0

You're going to need to change the way you approach this. You are currently trying to get the index of the value in the parameter array and use that in the target array. Of course, that's not going to work on an empty ArrayList!

What you need to do is start over using modern C#:

public static void GetPattern(List<string> values)
{
    var years = new Dictionary<string, List<string>>();

    foreach(var value in values)
    {
        if(value.Contains("2008")) 
        {
            if(!years.ContainsKey("2008")) years.Add("2008", new List<string>());
            years["2008"].Add(value);
        }

        if(value.Contains("2009")) 
        {
            if(!years.ContainsKey("2009")) years.Add("2009", new List<string>());
            years["2009"].Add(value);
        }

        // Add for each year you want to track.
    }

    // Do something with your pattern.
 }
The Sharp Ninja
  • 1,041
  • 9
  • 18
0

It's because you're trying to add a value to the array lists (the 2008 to 2012 ones) at position a, but they are empty, so a is out of range. You'd need to use the add function of the array list or use arrays, that you have set to a specific size (maybe the same size as the arrayList1). Hope this helps

Sandwich
  • 356
  • 7
  • 18
  • no it's not.. it's because to assign / add values to ArrayList you need to use the `.Add Method` check out my working answer below – MethodMan Dec 04 '15 at 15:43
  • I suggested using the add method of the arraylist. Or using arrays (with a set size) if the position need to match the arraylist1. – Sandwich Dec 04 '15 at 15:48
-1

Since your ArrayLists are empty there is no index exist. frist add some dummy data to create index and then add actual values. I hope this will solve your problem i've tested it is working

        private static void getPattern(ArrayList arrayList1)
    {
        ArrayList array_2008 = new ArrayList();
        ArrayList array_2009 = new ArrayList();
        ArrayList array_2010 = new ArrayList();
        ArrayList array_2011 = new ArrayList();
        ArrayList array_2012 = new ArrayList();

        for (int i = 0; i < arrayList1.Count; i++)
        {
            if (arrayList1[i].ToString().Contains("2008"))
            {
                int a = getIndex(arrayList1[i].ToString());
                for (int j = 0; j < a + 1; j++)
                {
                    array_2008.Add("empty");
                }
                array_2008[a] = arrayList1[i];
            }
            if (arrayList1[i].ToString().Contains("2009"))
            {
                int a = getIndex(arrayList1[i].ToString());
                for (int j = 0; j < a + 1; j++)
                {
                    array_2009.Add("empty");
                }
                array_2009[a] = arrayList1[i];
            }
            else if (arrayList1[i].ToString().Contains("2010"))
            {
                int a = getIndex(arrayList1[i].ToString());
                for (int j = 0; j < a + 1; j++)
                {
                    array_2010.Add("empty");
                }
                array_2010[a] = arrayList1[i];
            }
            else if (arrayList1[i].ToString().Contains("2011"))
            {
                int a = getIndex(arrayList1[i].ToString());
                for (int j = 0; j < a + 1; j++)
                {
                    array_2011.Add("empty");
                }
                array_2011[a] = arrayList1[i];
            }
            else if (arrayList1[i].ToString().Contains("2012"))
            {
                int a = getIndex(arrayList1[i].ToString());
                for (int j = 0; j < a + 1; j++)
                {
                    array_2012.Add("empty");
                }
                array_2012[a] = arrayList1[i];
            }
        }
Raider
  • 137
  • 8