在 Java 中将 HashMap 作为参数传递

新手上路,请多包涵

我有主类 Library 我在其中创建:

 HashMap<String, HashSet<String>> students_books = new HashMap<String, HashSet<String>>();

然后我将上课 Student 我将创建一个构造函数,它将 HashMap 作为参数,如下所示:

 public class Student {

    private Student(HashMap students_books){

然后,回到我的主类(库)中,我创建了一个 student 对象,我想将 HashMap 作为参数:

 Student student = new Student(*HashMap as parameter*);

我没有找到的是如何做到这一点以及 Student 类如何知道我传递的 HashMap 类型,例如 <String, HashSet<String>>

原文由 Fosh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.5k
2 个回答

知道我传递的是什么类型的 HashMap

首先,你的方法不是构造函数,因为它有返回类型,删除它的返回类型并公开你的构造函数。然后通过这样做强制他们传递你想要的 HashMap 类型

public class Student {

    public Student(HashMap<String, HashSet<String>> students_books){

然后像这样传递它们

HashMap<String, HashSet<String>> students_books = new HashMap<String, HashSet<String>>();
Student student = new Student(students_books);

原文由 Phi Luu 发布,翻译遵循 CC BY-SA 3.0 许可协议

回答你的问题 - “如何将 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){
..
}

原文由 Vinod Krishnan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题