Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a HashMap as parameter in Java

Tags:

java

hashmap

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

like image 421
Fosh Avatar asked Jun 11 '26 20:06

Fosh


1 Answers

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){
..
}
like image 190
Vinod Krishnan Avatar answered Jun 13 '26 09:06

Vinod Krishnan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!