I’ve searched but I did not find a good answer.
I’ve used an ArrayList object.I created an instance object, (example object X), I used that ArrayList as a parameter on constructor object X, but everytime I created an instance of object X, the ArrayList included the old values, didn’t create a new ArrayList.
I need to use add method like arraylist. This is the code:
public DataPacket(int hop, int TTL, ArrayList onetimevisit){
this.hop = hop;
this.TTL = TTL;
this.visited = onetimevisit;
}
in other looping process, DataPacket will meet object NodeRandom:
public NodeRandom(int id){
this.id = id;
}
then DataPacket will add the id of NodeRandom.
Is there an Object in Collection isn’t static?
Short answer:
change
to
Longer answer:
ArrayListsare not necessarilystatic. I think you’re incorrectly inferring that theArrayListmust somehow have been set to static from the fact that there is only one copy of theArrayListwhen you pass it in the way you’ve passed it. The thing to understand is that when you pass an object in Java (anArrayList, for example), you’re passing a reference to the object. A reference is something akin to a C-style pointer with the distinction that pointer arithmetic and such is not allowed. When you call a method and pass an object, the called method just gets a copy of the reference and not a copy of the object. Likewise, when you use the = operator to assign one object to another, you’re only assigning the references to equal each other, and there is still only one copy of the object. In your code, boththis.visitedandonetimevisitare references that come to point to the same object in memory.On the other hand,
ArrayListhas something that is somewhat akin to a copy constructor. This constructor, called in my sample code above, creates a shallow copy of the givenArrayList, which seems to be what you want. It is worth noting that anArrayListdoes not copy the objects added to it (it stores references to them), so perhaps what you really need is to create copies of the objects as well. This would be done by calling their copy constructors (if they allow copying by providing such a constructor) before inserting them into theArrayList.