Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can Vectors not have 0 index?

 
Rebecca Witmer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have code like that below in my program but when it gets down to line 126 (I marked it.) it crashes like this:

java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0

Can vectors not have 0 indices? If I change j to start from 1 it works but of course that's not what I want to do. It doesn't complain about i being 0 when I change j. What the heck?
Rebecca


import java.util.Vector;
import Jama.Matrix;

.
.
.

void FindCoefficients(Vector sdMatrices) {
Vector outerVector = new Vector();
for (int i = 0; i < sdMatrices.size(); i++) {
Matrix x = (Matrix) sdMatrices.elementAt(i);
for (int j = 0; j < sdMatrices.size(); j++) {
Matrix y = (Matrix) sdMatrices.elementAt(j);
Matrix xy = new Matrix(1, x.getColumnDimension());
for (int k = 0; k < x.getColumnDimension(); k++) {
double xElement = x.get(0, i);
double yElement = y.get(0, i);
double xyElement = xElement * yElement;
xy.set(0, k, xyElement);
}
Vector innerVector = new Vector();
System.out.print("J is " + j);
innerVector.set(j, xy); //Here's line 126
System.out.print("I is " + i);
outerVector.set(i, innerVector);
}
}

}
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not being familiar with the behavior of every class mentioned here, I can't tell you precisely what's happening, but basically, I can tell you that the "set" method lets you set an element that already has a value. You can't set element 0 of a zero-element Vector, because there is no element 0 yet.



works fine, because I'm using set() to change an element, not to add a new one. To add an element to an empty Vector, you have to use "add", not "set". Alternatively, you can use setSize() to fill the Vector with a certain number of null elements, then use set() to give them values.
 
Rebecca Witmer
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! That did it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic