英文:
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.
答案1
得分: 2
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());
}
英文:
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());
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论