Library我有我创建的主类:
HashMap<String, HashSet<String>> students_books = new HashMap<String, HashSet<String>>();
Run Code Online (Sandbox Code Playgroud)
然后我将在类Student中创建一个构造函数,该构造函数将 HashMap 作为参数,如下所示:
public class Student {
private Student(HashMap students_books){
Run Code Online (Sandbox Code Playgroud)
然后,回到我的主类(库),我创建一个student对象,我想将 HashMap 作为参数:
Student student = new Student(*HashMap as parameter*);
Run Code Online (Sandbox Code Playgroud)
我没有找到的是如何做到这一点以及类如何Student知道我传递的 HashMap 类型,例如,<String, HashSet<String>>
小智 5
为了回答你的问题 - “如何将 HashMap 作为参数传递”以及 Student 类如何知道类型,我提供了一种更通用和标准的方法来执行此操作
Map<K,V> books = new HashMap<K,V>(); // K and V are Key and Value types
Student student = new Student(books); // pass the map to the constructor
..
//Student Constructor
public Student(Map<K,V> books){
..
}
Run Code Online (Sandbox Code Playgroud)