Java Reference
In-Depth Information
2. Create an
ArrayList
and three instances of
Pupil
.
// Create an ArrayList.
ArrayList<Pupil> list = new ArrayList<Pupil> ();
// Create three instances of Pupil.
Pupil pupilOne = new Pupil("Susan", "A");
Pupil pupilTwo = new Pupil("Tom", "B");
Pupil pupilThree = new Pupil("Mary", "C");
3. Let's add the instance of
Pupil
to the
ArrayList
.
// Add the three instances of Pupil to the ArrayList.
list.add(pupilOne);
list.add(pupilTwo);
list.add(pupilThree);
4. Let's create a
HashMap
.
// Create a HashMap.
HashMap<String, Pupil> map = new HashMap<String, Pupil> ();
5. Let's retrieve the objects from the
ArrayList
. As you do so, you are going to
display their names and grades, and then you are going to add them to the
HashMap
using their names as a key.
for (int i = 0; i < list.size(); i++)
{
// Retrieve the pupils from the list, print their names.
Pupil pupil = list.get(i);
System.out.println(pupil.getName() + " earned a "
+ pupil.getGrade());
// Add them to the HashMap.
map.put(pupil.getName(), pupil);
}
6. You are now going to retrieve Tom's record and change his grade.
// Retrieves Tom from the HashMap and changes his grade.
Pupil pupilTom = map.get("Tom");
pupilTom.setGrade("A");