Giorgos Valamatsas
Giorgos Valamatsas

Reputation: 11

How I can link objects of one Class, to objects of another Class in Java?

I'm very new to programming and I need some help with my homework. I'like to know if the following is possible, and how. Let's say I have 2 classes, class Course and class Student. Many objects can be born from these classes, for example:

Course 1 obj Course 2 obj

Student 1 obj Student 2 obj Student 3 obj Student 4 obj

My question is, how I can relate the objects of Student class, to the objects of Course class? I want to make something like this:

Course 1 obj: Has objects Student 1, 2, 4
Course 2 obj: Has objects Student 2, 4

Our teacher said we should create another class that holds the Student objects for each Course object, but I don't understand how I must do this.

By far, I've created Student objects and stored them in an ArrayList. I did the same with Course objects. But I'm really stuck how to link one to another.

Upvotes: 1

Views: 1484

Answers (2)

Sachin Barnwal
Sachin Barnwal

Reputation: 74

If i am getting the question right, you want to map Course to Student(or list of student). There are several ways to do that and one of them is by using Hashtable< Key,Value >. In most basic sense, Hashtable is a table of Key/Value pairs in which each key is mapped/linked to a value.

a generic code sample related to the data given by you :

ArrayList<Student> list1 = new ArrayList<Student>();
list1.add(Student1);
list1.add(Student2);
list1.add(Student4);

ArrayList<Student> list2 = new ArrayList<Student>();
list1.add(Student2);
list1.add(Student4);

Hashtable<Course,ArrayList<Student>> hashTable = new 
Hashtable<Course,ArrayList<Student>>();

hashTable.put(Course1,list1);
hashTable.put(Course2,list2);

To get the value(Student list in this case) linked to the key(Course in this case), you just need to call the get(Key) method

ArrayList<Student> list3 = hastTable.get(Course1);//this will return the value(list1) mapped/linked to the key(Course1)

for more information on Hashtable refer to https://docs.oracle.com/javase/10/docs/api/java/util/Hashtable.html

Upvotes: 2

Borbat
Borbat

Reputation: 125

I think what you're looking for is to create a Course class and then inside it, create a list (ArrayList) of students (Student class). This Student class is a different class that is only used inside the Course.

Upvotes: 1

Related Questions