在Java中传递HashMap作为参数 [英] Pass a HashMap as parameter in Java

查看:377
本文介绍了在Java中传递HashMap作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中创建主类 Library :

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

然后,我将有一个类 Student ,在该类中,我将创建一个构造函数,该构造函数将HashMap作为这样的参数:

Then I'll have class Student where I'll make a constructor who will take the HashMap as a parameter like this:

public class Student {

    private Student(HashMap students_books){

然后,回到我的主类(库)中,我创建一个 student 对象,并在其中将HashMap用作参数:

then, back in my main class (Library) I create a student object where I want to put the HashMap as parameter:

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

我找不到的是如何执行此操作以及 Student 类如何知道我要传递的HashMap类型,例如,< String,HashSet< String>>

What I'm not finding is how I can do this and how the Student class knows what type of HashMap I'm passing, for example, <String, HashSet<String>>

推荐答案

知道我要传递的HashMap类型

knows what type of HashMap I'm passing

首先,您的方法不是构造函数,因为它具有返回类型,请删除其返回类型并公开您的构造函数.然后通过执行此操作强制他们传递您想要的HashMap类型

Firstly, your method is not a constructor since it has return type, remove its return type and public your constructor. Then just force them to pass what type of HashMap you want by doing this

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);

这篇关于在Java中传递HashMap作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆