[英]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. 基本上,我要做的就是在一个类中创建一个HashMap对象,使用循环在该类中构建它,然后能够将其调用到另一个类中。 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.
我尝试在类本身中声明它,然后在main()函数中构建它,但这不允许我在类外部访问它,因为它需要是静态的。
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
}
}
The HashMap
is an object. HashMap
是一个对象。 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 other = new Other() ;
Pass your map. 通过您的地图。
other.workOnMap( map ) ;
You can see this in action in the Oracle Java Tutorials . 您可以在Oracle Java教程中看到这一点。
Here is a complete example using four classes you might write yourself, MapDemo.java
and ReportTool.java
and LoggingTool.java
and EmployeePagingTool.java
. 这是一个使用四个类的完整示例,您可以自己编写四个类:
MapDemo.java
和ReportTool.java
以及LoggingTool.java
和EmployeePagingTool.java
。
In the public static void main
method, we create an instance of our app to get going. 在
public static void main
方法中,我们创建了应用程序的实例以进行操作。 This solves the chicken-or-the-egg paradox of OOP . 这解决了OOP的鸡或蛋悖论 。 Don't focus on this method as you are learning Java.
在学习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).
我将其更多地看作是黑客,是将我们从地球(主机,操作系统,文件,内存尚未分配)带到天堂的一个拐杖(一个奇妙的OOP天堂,只有干净的物体在周围漂浮,并相互传递消息) )。
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). 真正的动作是在
doIt
方法中,在该方法中,我们构建一个DayOfWeek
Map
枚举对象,该对象导致一个String
,该String
包含当日负责某些职责的员工姓名(例如,随叫随到的传呼机)。
An enum
means a set of named objects already instantiated for us. enum
是指已经为我们实例化的一组命名对象。 In this case we have seven DayOfWeek
objects already created for us, one for each day of the week. 在这种情况下,我们已经为我们创建了七个
DayOfWeek
对象,一周中的每一天都有一个。 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 . 这里没有什么太神秘的,枚举对象只是一个对象,而是一个对象,在该类中, JVM已预先加载了
new DayOfWeek
。
We populate our map with each day of the week as the key, and each DayOfWeek
key object leads to somebody's name. 我们以一周中的每一天为键填充地图,每个
DayOfWeek
键对象都指向某人的名字。 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). 我们从
ReportTool
类实例化的其他工具(此处未显示,因为其源代码与该演示无关)。 Ditto for LoggingTool
& EmployeePagingTool
. 同上
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. 在实际工作中,我们不太可能仅使用
String
对象作为员工姓名。 We would probably have an Employee
class, and objects of that class would be assigned. 我们可能会有一个
Employee
类,并将分配该类的对象。 In such a case we would declare our Map
as Map < DayOfWeek, Employee > weekCoverage
. 在这种情况下,我们将
Map
声明为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. 一种实现方法是在Java 9及更高版本中使用
Map.of
和Map.ofEntries
。 Another way is Collections.umodifiableMap
. 另一种方法是
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
. 关于多态的说明 …请注意,我们如何从
HashMap
的具体类中实例化一个对象,但是我们将对该对象的引用存储为更通用的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
. 我们就可以自由地后使用一些其他实施
Map
从HashMap
一些其他类型的地图,而不在我们MapDemo
不破坏我们的代码中ReportTool
。
Indeed we should change that MapDemo
code. 确实,我们应该更改该
MapDemo
代码。 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. 尽管上面的代码可以编译并运行良好,但是使用枚举对象作为键时,碰巧可以更好地实现
Map
接口。 The EnumMap
class uses less memory and executes faster than HashMap
when using enums as keys. 当使用枚举作为键时,
EnumMap
类使用的内存更少,并且比HashMap
执行得更快。 Both EnumMap
and HashMap
implement the same Map
interface. EnumMap
和HashMap
实现相同的Map
接口。
So we could months later spot this opportunity to tweak our MapDemo
code, without fearing any harm in the ReportTool
. 因此,我们可以在几个月后发现这个机会来调整我们的
MapDemo
代码,而不必担心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. OOP的主要优点之一是避免了古老的编程问题,因为一个地方的一点改动都会导致其他部分崩溃。
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 更新:我最终只是在Class1中的一个方法中构建并返回哈希图,然后在Class2中创建Class1的实例并调用该方法以返回哈希图
This was a rather simple solution, not sure why it was so difficult to find the answer. 这是一个相当简单的解决方案,不确定为什么很难找到答案。 Thanks to everyone who tried to help
感谢所有尝试提供帮助的人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.