Fosh
Fosh

Reputation: 121

Pass a HashMap as parameter in Java

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

Upvotes: 2

Views: 87086

Answers (4)

Phi Luu
Phi Luu

Reputation: 192

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

Upvotes: 3

Dilshod Shaymanov
Dilshod Shaymanov

Reputation: 71

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

Upvotes: 1

Vinod Krishnan
Vinod Krishnan

Reputation: 141

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

Upvotes: 5

rpfun12
rpfun12

Reputation: 89

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

Upvotes: 1

Related Questions