Keeping track of ArrayList objects
in
Programming Questions
•
3 years ago
If I make a number of objects in an ArrayList I can keep track of the objects by using their order within the list. But if objects is deleted other objects created later then the deleted objects will get a new "number" in the list and I can no longer track these objects.
My way to solve this problem is by giving all objects a variable called "id" and every time I want to reach an object in the list I need to check all objects if their id match with the one I'm looking for.
My question is:
Is there a more simple way of keeping track of your objects in an ArrayList?
Example (if I want to find the object which initially was number 6):
- stuff = new ArrayList();
-
class Thing{
-
int id;
-
Thing(int a)id = a;
-
}
-
- for(int i = 0; i < 10; i++) stuff.add(new Thing(i));
- Thing = thingThatIWantToUse;
- for(int i = 0; i < stuff.size(); i++){
- Thing tempThing = (Thing) stuff.get(i);
- if(tempThing.id == 5) thingThatImLookingFor = tempThing;
- i = stuff.size();
- }
Very simple but a bit annoying to do write all time. A more convenient way would be greatly appreciated.
Thanks,
Hampus
1