简体   繁体   中英

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 incremented. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM