Wednesday, April 20, 2011

Copying arraylist values within itself

Consider i have ArrayLists like these,

1){int[],int,int[]}
2){int[],int[],int} And i have a count, 'n'. If n is 3 then my arrayList should be,

1){int[],int[],int[],int,int[],int[],int[]}

2){int[],int[],int[],int[],int[],int[],int}

i.e The new ArrayList should contain 'n' times the Array int[].

From stackoverflow
  • For one thing, do you really have to use an ArrayList? The fact that you're holding different types of data in one collection suggests there's probably a better way of solving your problem. Anyway, you could do something like this:

    public static ArrayList DuplicateIntArrays(ArrayList input, int copies)
    {
        ArrayList ret = new ArrayList();
        foreach (object element in input)
        {
            if (element is int[])
            {
                for (int i=0; i < copies; i++)
                {
                    ret.Add(element);
                }
            }            
            else
            {
                ret.Add(element);
            }
        }
        return ret;
    }
    

0 comments:

Post a Comment