简体   繁体   中英

How do I build a HashMap in one class and then use it in another in Java?

Basically all I want to do is create a HashMap object in one class, build it in that class using a loop, and then be able to call it into another class. I'm not sure what I need to do to accomplish this. I tried declaring it in the class itself and then building it in the main() function, but that doesn't allow me to access it outside of the class because it would need to be static.

Here is some psuedocode of what my thought process is:

public class Class1 {
    public Map<> map = new HashMap<>();

    public static void main(String[] args) {
    //build hashmap here using map.put etc
    }

public class Class2 {
    public static void main(String[] args) {
    //get the map using Class1.map
    }
}

Pass object reference in method call

The HashMap is an object. So pass a reference to it in a method call of an object of the other class.

Make your map.

Map map = new HashMap() ; 
map.put( … ) ;

Make your other object. Here we imagine a class named Other that you wrote.

Other other = new Other() ;

Pass your map.

other.workOnMap( map ) ;

You can see this in action in the Oracle Java Tutorials .

Example

Here is a complete example using four classes you might write yourself, MapDemo.java and ReportTool.java and LoggingTool.java and EmployeePagingTool.java .

In the public static void main method, we create an instance of our app to get going. This solves the chicken-or-the-egg paradox of OOP . Don't focus on this method as you are learning Java. I think of it more as a hack, a crutch to get us from earth (host computer, operating system, files, memory not yet allocated) to heaven (a wonderful OOP paradise of nothing but clean objects floating around and passing messages to each other).

The real action is in the doIt method where we build a Map of DayOfWeek enum objects leading to a String containing the name of an employee covering some responsibility that day (such as carrying on-call pager).

An enum means a set of named objects already instantiated for us. In this case we have seven DayOfWeek objects already created for us, one for each day of the week. Nothing too mysterious here, an enum object is just an object but an object where new DayOfWeek was already called for you ahead of time, when the class was loaded by the JVM .

We populate our map with each day of the week as the key, and each DayOfWeek key object leads to somebody's name. We have exactly one name assigned to each day of the week.

Lastly, we hand off this map to another object for analysis to generate a report that gets sent to the boss. That other tool we instantiate from the class ReportTool (not shown here as its source code is irrelevant to this demo). Ditto for LoggingTool & EmployeePagingTool .

package com.basilbourque.example;

import java.time.DayOfWeek;
import java.util.HashMap;
import java.util.Map;

public class MapDemo {

    public static void main ( String[] args ) {
        MapDemo app = new MapDemo();
        app.doIt();
    }

    private void doIt ( ) {
        int initialCapacity = DayOfWeek.values().length;
        Map < DayOfWeek, String > weekCoverage = new HashMap <>( initialCapacity );

        weekCoverage.put( DayOfWeek.MONDAY , "Stuart" );
        weekCoverage.put( DayOfWeek.TUESDAY , "Wendy" );
        weekCoverage.put( DayOfWeek.WEDNESDAY , "Lisa" );
        weekCoverage.put( DayOfWeek.THURSDAY , "Jesse" );
        weekCoverage.put( DayOfWeek.FRIDAY , "Marvin" );
        weekCoverage.put( DayOfWeek.SATURDAY , "Janet" );
        weekCoverage.put( DayOfWeek.SUNDAY , "Jarrod" );

        System.out.println( weekCoverage );

        ReportTool reportTool = new ReportTool();
        reportTool.makeHtmlSummaryOfWeekCoverageAndEmailToBoss( weekCoverage );

        LoggingTool loggingTool = new LoggingTool();
        loggingTool.logWeekCoverage( weekCoverage );

        EmployeePagingTool employeePagingTool = new EmployeePagingTool();
        employeePagingTool.sendTextMessagesForWeekCoverage( weekCoverage );

    }
}

In real work, we would not likely be using mere String objects for the employee names. We would probably have an Employee class, and objects of that class would be assigned. In such a case we would declare our Map as Map < DayOfWeek, Employee > weekCoverage .

You may want to prevent changes to the map. One way to do that is use of Map.of & Map.ofEntries in Java 9 and later. Another way is Collections.umodifiableMap .


A note on polymorphism … Notice how we instantiate an object from the concrete class of HashMap , but we store a reference to that object as the more general Map . We are then free to later use some other implementation of Map from HashMap to some other kind of map without in our MapDemo without breaking our code in ReportTool .

Indeed we should change that MapDemo code. While that code above compiles and runs well enough, there happens to be a better implementation of the Map interface when using enum objects as the key. The EnumMap class uses less memory and executes faster than HashMap when using enums as keys. Both EnumMap and HashMap implement the same Map interface.

So we could months later spot this opportunity to tweak our MapDemo code, without fearing any harm in the ReportTool . One of the major benefits to OOP is avoiding the age-old programming problem where one little change in one place causes other parts to blow-up.

We change these two lines:

        int initialCapacity = DayOfWeek.values().length;
        Map < DayOfWeek, String > weekCoverage = new HashMap <>( initialCapacity );

…to this single line:

        Map < DayOfWeek, String > weekCoverage = new EnumMap( DayOfWeek.class );

None of the other code need change.

Update: I ended up just building and returning the hashmap in one method in Class1, then creating an instance of Class1 in Class2 and calling the method to return the hashmap

This was a rather simple solution, not sure why it was so difficult to find the answer. Thanks to everyone who tried to help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM