Spaces:
Running
Running
ArrayList, HashMap
Browse files
Week 4: Writing classes/14A. Objects in data structures
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
It is often useful to store objects in data structures.
|
| 2 |
+
An example of how to deal with objects created from the Student class in a list:
|
| 3 |
+
|
| 4 |
+
ArrayList<Student> students = new ArrayList<>();
|
| 5 |
+
|
| 6 |
+
Student s1 = new Student("Sam", "12345", 40);
|
| 7 |
+
students.add(s1);
|
| 8 |
+
|
| 9 |
+
System.out.println(students.get(0).getName());
|
| 10 |
+
|
| 11 |
+
Program outputs:
|
| 12 |
+
Sam
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
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:
|
| 21 |
+
|
| 22 |
+
HashMap<String, Course> courses = new HashMap<>();
|
| 23 |
+
|
| 24 |
+
Course oop = new Course("Object-oriented programming", 5);
|
| 25 |
+
|
| 26 |
+
// let's use course code as the key
|
| 27 |
+
courses.put("TKO_2003", oop);
|
| 28 |
+
|
| 29 |
+
System.out.println(courses.get("TKO_2003").getIdentifier());
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Program outputs:
|
| 33 |
+
Object-oriented programming
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Objects are handled in the data structure in the usual way.
|
| 41 |
+
The following method takes a list of students as its parameter and returns the total number of credits:
|
| 42 |
+
|
| 43 |
+
public static int combinedPoints(ArrayList<Student> students) {
|
| 44 |
+
int points = 0;
|
| 45 |
+
|
| 46 |
+
// The extended for-loop is handy here too
|
| 47 |
+
for (Student student : students) {
|
| 48 |
+
points += student.getStudypoints();
|
| 49 |
+
}
|
| 50 |
+
return points;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
|