Question

    import java.util.*;

    class A
    {
        private ArrayList <B> bList;
        private Random generator = new Random();

        A(List<B> initialList)
        {
            bList = new ArrayList<B> ();
            int listSize = initialList.size();
            bList.ensureCapacity(listSize);

            for (B b : initialList)
            {
                int bIndex = generator.nextInt(listSize);
                bList.add(bIndex , b);
            }
        }
    }

    class B
    {
    }

I ended up with a new error that is an out of range error when I insert blist.add(bIndex , b);

After Debugging it appears that ensureCapacity doesn't do its job.

Was it helpful?

Solution

Look at the documentation of the add method:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())

It does not make sense to put an element into a list at a position that would cause holes in the list.

The ensureCapacity just makes room for such many elements. It does not mean they are actually there.

With this change it should work:

int bIndex = generator.nextInt(bList.size()+1);

OTHER TIPS

capacity is distinct from size. You ensure that the new list has enough internal capacity for the index you are using for the add calls, but then you call add with an index (potentially, and likely) greater than the lists's size.

You will get this error randomly. Because you create the index(bIndex) using random class. It will generate the index with in the list size you mention(int bIndex = generator.nextInt(listSize)). Sometimes it will generate the random number which is more than 0. At that time you will get this error. If it creates 0, then it wont give the error.

You can use the for loop instead of foreach.

for (int i = 0; i < listSize; i++) {
   B b = initialList.get(i);
   bList.add(i, b);
   System.out.println(bList.toString());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top