开发者

Elements in java ArrayList taking up two places

I have made a LinkedList to store State objects which is a class I have created. I can add states to the list as expected, but whenever I try the size() method on the list it always returns twice the amount of elements I have added. Why is it doing this and how can I then use the ge开发者_运维问答t(n) method if each element has 2 values of n?

Here's the code used to create and add to the list:

static ArrayList<State> stateTable = new ArrayList<State>();
stateTable.add(new State(new Item(0,0)));

I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable. Thanks


I will add that the adding to the list is done inside the constructor for State objects so that all created States get put in the stateTable.

If you already add the states to your list inside the constructor and additionally have the line

stateTable.add(
    new State(new Item(0,0))     // <= first time inside new State(...)
);                               // <= second time explicitely in this line

then you are indeed adding it twice.


search for .add( and make sure you are not calling it in multiple places.

If your ArrayList is not marked as private mark it as private.

If you return your ArrayList from a method do return a read-only version via: Collection.unmodifiableList(stateTable);

If you load the data in one method or the constructor and do not intend to do it anywhere else than do it something like:

private static final List<State> stateTable;

static
{
    final List<State> temp;

    temp = new ArrayList<State>();
    temp.add(new State(new Item(0,0)));

    stateTable = Collections.unmodifiableList(stateTable);
}

Using the unmodifiableList will cause your program to crash if you add objects into it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜