0

I've read the documentation and looked at scores of SO questions and still can't create a vector of vectors without running into the ArrayIndexOutofBounds exception. For some context, I am creating a matrix, where each slot contains a reference to an edge, representing a flight from a source to a destination . Following one SO response, I set up my vector as follows.

    Iterator<Edge> iter = array.iterator();
    private Vector<Vector<Edge>> matrix = new Vector<Vector<Edge>>(9);
    for (int i=0;i<9;i++){
        matrix.add(i,new Vector<Edge>(9));
    }

    while (iter.hasNext()) {
        Edge e = iter.next();
        int s = e.source; //row
        int d = e.destination; //col    
        Vector<Edge> row = matrix.get(s);
        int size = row.size();
        row.add(d, e); // Array Out of Bounds Exception
    }

I believe I have initialized my inner and outer vectors and don't understand why the size of the vector is still zero. Do I have to initialize all the elements to null before I can start putting and getting elements? I would really appreciate your help.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
I Like
  • 1,711
  • 2
  • 27
  • 52

2 Answers2

2

new Vector<Edge>(9) creates an empty Vector of capacity 9. Therefore, calling add(d,e) for such a Vector when d is not 0 will throw ArrayIndexOutOfBoundsException.

To initialize each row Vector with null values, use:

for (int i = 0; i < 9; i++) {
    Vector<Edge> v = new Vector<>(9);
    matrix.add(v);
    for (int j = 0; j < 9; j++)
        v.add(null);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    New duplicated questions do not necessarily need new answers ;-) – GhostCat May 22 '18 at 05:29
  • why doesnt vector initialize to null by default when array defaults to zero values? – I Like May 22 '18 at 05:33
  • 1
    @st4rgut it does create a backing array of the specified length (9), which by default contains `null`s. However, the `Vector` is considered empty until you add elements to it. – Eran May 22 '18 at 05:38
  • 1
    This answer could probably be improved by mentioning [Vector.setSize()](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html#setSize-int-). – Ilmari Karonen Jan 07 '19 at 02:12
0

Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
Parameters: initialCapacity the initial capacity of the vector
Throws: java.lang.IllegalArgumentException if the specified initial capacity is negative

    public Vector(int initialCapacity) {
         this(initialCapacity, 0);   
}
Ng Sharma
  • 2,072
  • 8
  • 27
  • 49