An array holds homogenous data, i.e. usually the class of everything in every cell of an array is the same. You will likely not want to store a person's name and his shoe size in fields of the same type, so... let's drop one of the array's dimensions. You should declare a class called something like Person
and specify within it all the attributes you want to store for a person. Having done that, you will only be wanting to store a one dimensional array (or something) of Person
.
Next, note that arrays are fixed in size. If you want to extend an array, you would need to allocate a new, bigger array, copy the contents of the old one into the new one and then go on working with the new one in place of the old one.
That's a lot of work, and error prone. In the modified words of Apple, there's a class for that! The older qualified class was Vector
, a class where you could store objects and that would grow every time you add a new object to it. Nowadays, the class to use for this (it's a bit more efficient) is ArrayList
. Same thing: You do
ArrayList<Person> myList = new ArrayList<Person>();
and then you can repeatedly
newPerson = new Person("Bruce", "Wayne", 1972, "Gotham City");
myList.add(newPerson);
and you can access folks in the list by doing
int personNumber = 0;
Person retrievedPerson = myList.get(personNumber);
or even
for (Person someone : myList) {
System.out.println(someone);
}
EDIT
OK, to store people with an ID and access them by that ID assuming the person ID is an integer, some appropriate code would be:
TreeMap<Integer, Person> myMap = new TreeMap<Integer, Person>();
newPerson = ...
myMap.put(newPerson.getId(), newPerson);
then you can retrieve it with
Person p = myMap.get(id);