File size: 1,182 Bytes
82757ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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;
}