In Java, all instances of person are linked to an object
•
Java
I'm currently writing a program, but I found a problem The problem is that in the following loop, all instances of the person class are attached to an instance of item What I want is that everyone has their own things Do you have any suggestions?
Class simulation:
public void simulate(int days){ for(int i=0;i<days;i++) { int persons = 10; for(int j=0;j<persons;j++){ Person person = new Person(); Item item = new Item(); person.setItem(item); } } }
Class personnel:
private Item item; public void setItem(Item item) { this.item = item; }
Solution
But that's what you're doing You are creating an instance of person, and each newly created instance will receive the newly created item instance
for(int j=0;j<persons;j++){ Person person = new Person(); Item item = new Item(); person.setItem(item); }
You just don't keep references to all the objects you've created So sooner or later they will be garbage collected Your cycle is equivalent to
for(int j=0;j<persons;j++){ new Person().setItem(new Item()); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码