Pass a HashMap as parameter in Java

血红的双手。 提交于 2021-02-08 10:12:44

问题


I have the main class Library where I create:

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

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

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

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


回答1:


knows what type of HashMap I'm passing

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

and then passing them like this

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



回答2:


To answer your question - "How to pass HashMap as a parameter" and how Student class know the type I am providing a more generic and standard way of doing this

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){
..
}



回答3:


In your Student class constructor(which currently a method, since it has a return type), the argument is not utilizing generic type.

Please change it to the following.

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

}

This will ensure type safetey during compile time




回答4:


What you did is a private method, not a constructor. change your method to this:

public Student(HashMap<String, HashSet<String>> student_books) {
    //your code here
} 

I this way it will a true constructor you wanted, hope this will help



来源:https://stackoverflow.com/questions/42709454/pass-a-hashmap-as-parameter-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!