开发者

Vector ArrayIndexOutOfBounds

I'm having an ArrayIndexOutofBounds exception with the following code. The exception is thrown at the line where Node nodeJ = vect.get(j)

but it does not make sense to me since j is definitely smaller than i and Node nodeI = vect.get(i) does not throw any exception.

any help is appreciated.

public static Vector join(Vector vect) throws ItemNotFoundException {

    Vector<Node> remain = vect;
    for (int i = 1; i <开发者_Go百科; vect.size(); i++) {
        Node nodeI = vect.get(i);
        for (int j = 0; j < i; j++) {//traverse the nodes before nodeI
            Node nodeJ = vect.get(j);

            if (nodeI.getChild1().getSeq().equals(nodeJ.getSeq())) {
                nodeI.removeChild(nodeJ);
                nodeI.setChild(nodeJ);
                remain.remove(j);
            }
            if (nodeI.getChild2().getSeq().equals(nodeJ.getSeq())) {
                nodeI.removeChild(nodeJ);
                nodeI.setChild(nodeJ);
                remain.remove(j);
            }
        }
    }
    return remain;
}


You are removing elements from the same vector you are iterating over, via an alias reference, remain. If you want to use a copy instead, you should have

Vector<Node> remain = new Vector<Node>(vect);


What happens if in your inner loop you remove more than i - j Nodes from the vector? You will end up with j > vect.size().

Probably best to change the condition in the second for loop to j < i && j < vect.size(), however I think there is something flawed about an algorithm which involves double-iterating over a collection to remove elements from it while you are iterating over it.


You're removing things from vect while you're iterating over it. Are you sure that's what you want to do?

Remember that this line:

Vector<Node> remain = vect;

does not create a copy of vect. Remove something from remain and it'll be removed from vect too, because the two names refer to the same actual object.


You should use Iterator. Look to documentation http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html

You can read:

Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.


You are removing items from your vector.

Use some logging to output the contents of the vector on each iteration of the inner loop and you'll see what's going on.


When you remove an item from the vector (which you do), then the length of the vector changes. The problem is that the code after the removal has had so many nodes removed that it's now using indexes which are no longer valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜