Dark Archon Dark Archon - 2 months ago 34
Java Question

Finding an object by ID (Java)

I have a class Person, which have unique id of person (type int) for each Person object. I also have a static method isAlreadyStored(String name), which should check if a person with this name was already created. I can't solve this one by creating a list for all created Person objects, because I get error "non-static variable cannot be referenced from a static context", but I don't have any other idea how to iterate over all Person objects to find one with a given name. How do I approach this?


Apparently for solving your problem you need a list of all created instances for Person class. You should store that in a static variable, and then search on it. Something like this:

final static allPeople List<Person> = new ArrayList<Person>();

Then you could search on that list with something like this:

if (allPeople.contains(aPerson){