Section 3.4 Builtins example: Grades
As an example of these two concepts, let’s look at a simple example, that builds on the
LetterGrade
class we saw in Subsection 2.2.1. Here it is again as a reference:public class LetterGrade {
public String letter;
public double points;
public LetterGrade(String letter, double points) {
this.letter = letter;
this.points = points;
}
...
}
We will now create a class that is responsible for managing the grades in our application. We will call this class a
GradeManager
for lack of a better term. This class will do two things:- It holds a list of all the grades, in increasing order, and can return a copy of that list on request
- It holds a map of the grades, using their letters as the keys. Using this map, it can quickly return to its user the grade object corresponding to a particular letter.
Let’s take a look. For simplicity we will only add a few letter grades, and omit plus/minus:
public class GradeManager {
private List<LetterGrade> grades = new ArrayList<>();
private Map<String, LetterGrade> gradesByLetter = new HashMap<>();
GradeManager() {
addGrade("W", 0.0);
addGrade("F", 0.0);
addGrade("D", 1.0);
addGrade("C", 2.0);
addGrade("B", 3.0);
addGrade("A", 4.0);
}
private void addGrade(String letter, double points) {
LetterGrade grade = new LetterGrade(letter, points);
grades.add(grade);
gradesByLetter.put(letter, grade);
}
List<LetterGrade> getGrades() {
return new ArrayList<>(grades);
}
LetterGrade gradeForLetter(String letter) {
return gradesByLetter.getOrDefault(letter, null);
}
}
You should by now have a basic understanding of what this code does; if you don’t, refer to the corresponding documentation and the previous sections. Notice how we use a helper function
addGrade
to create a new grade and add it to the two entities used to represent the grades. It is marked as private since no-one else needs to know about it.