Alex Yánez
Alex Yánez

Reputation: 41

how to declare and fill a vector of objects inside another vector of objects in java?

How to declare and fill a vector of objects inside another vector of objects? Also...

How to declare and fill a String vector inside another object vector?

For example: I have a vector of objects (Student), I need another vector of objects (Subjects) that is inside it ... Also a list (Notes). How would you declare them? How would you fill them?

Please, examples.

Upvotes: 0

Views: 402

Answers (1)

loganrussell48
loganrussell48

Reputation: 1864

List<Object> outterList = new ArrayList<>();
List<Object> innerList = new ArrayList<>();
outterList.add(innerList);
List<String> stringList = new ArrayList<>();
outterList.add(stringList);

This does what you've said, but I don't think it's what you meant.

You'd most likely want something like this

List<List<String>> outterList = new ArrayList<>();
List<String> listOfStrings = new ArrayList<>();
outterList.add(listOfStrings);

This created a list of lists that contain strings. You can add as many string lists as your memory will allow. You can have lists of different types by changing the Type inside the angle brackets.

EDIT: To achieve what you're asking I would set up the Student class like so:

class Student{
    List<Subject> subjects;
    List<Note> notes;

    //getters and setters
}

Then, when you create or have a list of Students, and you want to see their subjects, just use something like this:

List<Student> students = ... *retrieve list of students here*
for( Student s : students ){
    for(Subject sub : s.getSubjects())
        System.out.printf("Student: %s    Subject: %s%n", s.toString(), sub.toString());
}


Upvotes: 2

Related Questions