Java,如何在main之外创建哈希映射,但在main或其他方法中引用它
Java,如何在main之外创建哈希映射,但在main或其他方法中引用它 导入java.util.*Java,如何在main之外创建哈希映射,但在main或其他方法中引用它,java,Java,Java,如何在main之外创建哈希映射,但在main或其他方法中引用它 导入java.util.* import java.util.Map.Entry; //创建哈希映射 HashMap hm=新的HashMap(); //将元素放入地图 hm.put(“约翰·多伊”,新双(3434.34)); hm.put(“汤姆·史密斯”,新双(123.22)); hm.put(“简·贝克”,新双人(1378.00)); hm.put(“托德大厅”,新双人房(99.22)); hm.put(“拉尔夫·史
import java.util.Map.Entry;
//创建哈希映射
HashMap hm=新的HashMap();
//将元素放入地图
hm.put(“约翰·多伊”,新双(3434.34));
hm.put(“汤姆·史密斯”,新双(123.22));
hm.put(“简·贝克”,新双人(1378.00));
hm.put(“托德大厅”,新双人房(99.22));
hm.put(“拉尔夫·史密斯”,新双(-19.08));
类HashMapDemo
{
公共静态void main(字符串参数[])
{
//获取一组条目
Set>Set=hm.entrySet();
//获取迭代器
迭代器>i=set.Iterator();
//显示元素
while(i.hasNext())
{
条目me=i.next();
System.out.print(me.getKey()+“:”);
System.out.println(me.getValue());
}
System.out.println();
//把1000英镑存入约翰·多伊的账户
双重平衡=hm.get(“John Doe”).doubleValue();
hm.put(“约翰·多伊”,新双人(余额+1000));
System.out.println(“约翰·多伊的新平衡:+hm.get(“约翰·多伊”));
}
}
问题在于您试图从静态main访问实例值。要解决这个问题,只需将HashMap设置为静态
static HashMap<String, Double> hm = new HashMap<String, Double>();
static {
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
}
我同意Glitch的观点,但您也可以创建一个类来设置哈希映射,并使用函数
getHM()
返回它。然后,您只需在主菜单中创建:
- 该类的对象,例如
Test Test=新测试()代码>
- 一个新的HashMap,并将其赋值为getHM(),例如
HashMap hm=test.getHM()代码>
public class Test {
HashMap<String, Double> hm;
public Test() {
hm = new HashMap<String, Double>();
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
}
public HashMap<String, Double> getHM() {
return hm;
}
}
公共类测试{
HashMap-hm;
公开考试(){
hm=新的HashMap();
hm.put(“约翰·多伊”,新双(3434.34));
hm.put(“汤姆·史密斯”,新双(123.22));
hm.put(“简·贝克”,新双人(1378.00));
hm.put(“托德大厅”,新双人房(99.22));
hm.put(“拉尔夫·史密斯”,新双(-19.08));
}
公共HashMap getHM(){
返回hm;
}
}
我想说,解决方案的选择取决于您的需求,但如果这是您唯一的问题,那么glitch提供的解决方案可能是最简单/最好的
使用static关键字可以检索HashMap,而无需创建任何对象的实例。我相信这在内存使用方面会更好(但我不是优化方面的专家…。+1为好的替代解决方案。当你在显示代码的时候,当你在混合空格和制表符的时候,你会看到奇怪的格式。非常感谢@PLB。在我继续开发我的程序时,我可能会使用您的解决方案。@Glitch感谢您在格式化方面的帮助。只有我在这里的第二天,还有很多东西要学!很高兴知道。你可以接受答案,这样别人就会知道你已经找到了解决方案
Set<Entry< String, Double> > set = hm.entrySet();
public class Test {
HashMap<String, Double> hm;
public Test() {
hm = new HashMap<String, Double>();
hm.put("John Doe", new Double(3434.34));
hm.put("Tom Smith", new Double(123.22));
hm.put("Jane Baker", new Double(1378.00));
hm.put("Todd Hall", new Double(99.22));
hm.put("Ralph Smith", new Double(-19.08));
}
public HashMap<String, Double> getHM() {
return hm;
}
}