开发者

Weird Object/class behaviour in Java

I have an array of Group. When I call increment, to increment the id of the object (in A) all the IDs of all the object in the array are being incre开发者_JAVA百科mented. Anyone know why please?

 Group [] groups = new Group [g];
    groups[0] = group;
    for (int i=1; i<g;i++){
        groups[i] = groups[i-1];
        groups[i].increment();              .......... A

    }


    public void increment() {
         this.groupid = this.groupid++;
    }


for (int i=1; i<g;i++){
    groups[i] = groups[i-1];
    groups[i].increment();
}

Every index of your array refers to the same Group object.


Because you're simply copying references to all the elements of the array. All the elements contain the same instance of Group but different references.

You should either create a new Group object each time in the loop or use a copy constructor.


There are two problems.

First the increment method does not actually work. It should probably be:

 public void increment() {
     this.groupid++;
 }

Otherwise it wouldn't actually change.

The second problem was already mentioned by other answers, that is, you actually have only one Group object and many references to that one object.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜