I am merging two Vector analogs together by appending the second to the first, and getting an exception. Why?

StackOverflow https://stackoverflow.com/questions/19017204

Question

I am creating a Vector analog to learn a little bit more about one-dimensional data structures.

The problem is this: my merge() method (which is basically an extension of my append() method) is throwing an ArrayOutOfBoundsException.

The MyVector class itself is lengthy, so I'll post the relevant parts.

Class/Object fields:

public class MyVector implements Cloneable 
{
   private Object[] data;
   private static final int INITIAL_CAPACITY = 100;
   private int size;

The default (only one currently) constructor, along with the append() method:

public MyVector()
{
    data = new Object[INITIAL_CAPACITY];
    size = 0;
}
public void append(Object element)
{
    if (size == data.length)
        expand();
    data[size++] = element;
}

The merge() method:

public void merge(MyVector vector2)
{
    for(int i = this.size; i < (this.size + vector2.size()); ++i)
        this.append(vector2.data[i]);
    this.size += vector2.size();
}

The place where it's called:

vec.merge(vecCopy);

vec is created as a MyVector object earlier in the class, while vecCopy is a copy of the references to the data in vec.

That's all of the relevant code. I imagine the answer is obvious, but for whatever reason I can't see it.

Was it helpful?

Solution

for(int i = this.size; i < (this.size + vector2.size()); ++i)

The index i can get over vector2.size(), i.e, index out of bounds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top