GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Can Vectors not have 0 index? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Can Vectors not have 0 index?" Watch "Can Vectors not have 0 index?" New topic

Can Vectors not have 0 index?

Rebecca Witmer
Ranch Hand

Joined: Sep 10, 2004
Posts: 46
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?

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);


SCJP 1.4
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24187

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.

[Jess in Action][AskingGoodQuestions]
Rebecca Witmer
Ranch Hand

Joined: Sep 10, 2004
Posts: 46
Thanks! That did it.
GeeCON Prague 2014
subject: Can Vectors not have 0 index?