Spaces:
Running
Running
| It is often useful to store objects in data structures. | |
| An example of how to deal with objects created from the Student class in a list: | |
| ArrayList<Student> students = new ArrayList<>(); | |
| Student s1 = new Student("Sam", "12345", 40); | |
| students.add(s1); | |
| System.out.println(students.get(0).getName()); | |
| Program outputs: | |
| Sam | |
| In the same way, you could define, say, a scatterplot where the keys are strings and the values are objects from the 'Course' class above: | |
| HashMap<String, Course> courses = new HashMap<>(); | |
| Course oop = new Course("Object-oriented programming", 5); | |
| // let's use course code as the key | |
| courses.put("TKO_2003", oop); | |
| System.out.println(courses.get("TKO_2003").getIdentifier()); | |
| Program outputs: | |
| Object-oriented programming | |
| Objects are handled in the data structure in the usual way. | |
| The following method takes a list of students as its parameter and returns the total number of credits: | |
| public static int combinedPoints(ArrayList<Student> students) { | |
| int points = 0; | |
| // The extended for-loop is handy here too | |
| for (Student student : students) { | |
| points += student.getStudypoints(); | |
| } | |
| return points; | |
| } | |