Java 中奇怪的对象/类行为
我有一组组。当我调用increment时,要增加对象的id(在A中),数组中所有对象的所有ID都会增加。请问有人知道为什么吗?
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++;
}
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++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
数组的每个索引都引用同一个 Group 对象。
Every index of your array refers to the same Group object.
因为您只是复制对数组所有元素的引用。所有元素都包含相同的 Group 实例,但引用不同。
您应该每次在循环中创建一个新的 Group 对象,或者使用复制构造函数。
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.
有两个问题。
首先,增量方法实际上不起作用。可能应该是:
否则它实际上不会改变。
第二个问题已经在其他答案中提到过,也就是说,您实际上只有一个 Group 对象和对该一个对象的许多引用。
There are two problems.
First the increment method does not actually work. It should probably be:
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.