Search code examples
javaarraylistinstantiation

Reinstantiating ArrayList with initial capacity


I already have two ArrayLists of vertices for what is basically a graph data structure. The first being the vertices, or intersections, and the second being the edges, called roads. I am trying to reinstantiate them when I know how many vertices/edges are in the graph.

int line = 0;
        while(reader.hasNextLine()){
            String thisLine = reader.nextLine();
            System.out.println(thisLine + " line: " + line);
            if(line == 0){

                numIntersections = Integer.parseInt(thisLine.split("\\s+")[0]);
                intersections = new ArrayList<Intersection>(numIntersections);
                System.out.println("numIntersections: " + numIntersections + " intersections size: " + intersections.toArray().length);
                numRoads = Integer.parseInt(thisLine.split("\\s+")[1]);
                roads = new ArrayList<Road>(numRoads);
            }
            else if(line > 0 && line < numIntersections + 1){
                int first = Integer.parseInt(thisLine.split("\\s+")[0]);
                int second = Integer.parseInt(thisLine.split("\\s+")[1]);
                int third = Integer.parseInt(thisLine.split("\\s+")[2]);
                intersections.add(first, new Intersection(second, second, third));
            }
            else if(line > numIntersections + 1){
                roads.add(new Road(intersections.get(Integer.parseInt(thisLine.split("\\s+")[0])), intersections.get(Integer.parseInt(thisLine.split("\\s+")[1]))));
                intersections.get(Integer.parseInt(thisLine.split("\\s+")[0])).addNeighbor(intersections.get(Integer.parseInt(thisLine.split("\\s+")[1])));
            }
            line++;
        }

You can see that in the first if statement I reinstantiate the ArrayList when I know the numIntersections. I do the same for when I know the number of roads.

However, when I try to add a new intersection to the list in the first else if statement, it throws an out of bounds exception. Which should not occur because the capacity is set to the numIntersections.


Solution

  • Capacity does not equal size.

    A newly created ArrayList with a capacity of 10, will have a backing array that allows for the allocation of 10 elements, but its size will still be zero. Addressing any element in that ArrayList will result in an IndexOutOfBoundsException, although the add() method will let you add an element at index 0.

    As the Javadoc for the ArrayList.add() method states:

    Throws:

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

    This answer shows how an ArrayList can be initialized with a specific number of values.