2013-12-15 96 views
0

我正在学习Java中的HashMap,所以我有一个简单的Java程序来创建一个帐户。我的问题是当涉及到将新帐户存储到集合中时,我正在尝试使用散列映射来执行此操作,但无法确定要去哪里。将对象添加到集合

HashMap<String,CurrentAccount> m = new HashMap<String,String>(); 
if (Account.validateID(accountID)) { 
    CurrentAccount ca = new CurrentAccount(cl,accountID, sortCode, 0); 

我不能确定下一阶段的这个帐户添加到我已经尝试了几种不同的方法,但总是有错误最终HashMap中。

回答

3

您的实例化语句出现错误。地图的类型是HashMap<String, CurrentAccount>,但您正在实例化HashMap<String,String>

为了解决这个问题,改变你的实例化语句对应到地图的类型,如下所示:

HashMap<String, CurrentAccount> m = new HashMap<String, CurrentAccount>(); 

或者,如果您使用的是JDK 1.7+,你可以使用钻石符号代替(见Generic Types更多信息):

HashMap<String, CurrentAccount> m = new HashMap<>(); 

为项目添加到地图中,你可以使用Map#put(K, V)

m.put(accountID, ca); 

为了得到一个值,你可以使用Map#get(Object)

CurrentAccount ca = m.get(accountID); 

有关映射的更多信息,请参见JDK 1.7 Map documentation


至于由OP在这个答案的意见中提出,为了访问多个方法地图(或任何其他类型)的问题,它必须被声明为类领域:

public class TestClass { 
    Map<String, CurrentAccount> accountMap; 

    public TestClass() { 
     accountMap = new HashMap<String, CurrentAccount>(); 
    } 

    public void method1() { 
     // You can access the map as accountMap 
    } 

    public void method2() { 
     // You can also acces it here 
    } 
} 
+0

感谢,这使得很多更有意义吧!我唯一的问题是,如果我已经在一个函数中完成了所有这些,那么是否有可能在另一个函数中从哈希映射中调用一个值? – UniqueName

+0

您必须将哈希映射声明为类的字段。我会更新我的答案以包含一个例子。 –

+0

非常感谢我现在已经掌握了这一切!干杯! – UniqueName

1

当您将值输入到两个不同的对象时,映射声明不正确。更改声明:

Map<String,CurrentAccount> m = new HashMap<String,CurrentAccount>(); 

然后,假设该accountID值是一个字符串,它应该是那样简单......

m.put(accountID, ca); 

总之你必须:

Map<String,CurrentAccount> m = new HashMap<String,CurrentAccount>(); 

if (Account.validateID(accountID)) { 
    CurrentAccount ca = new CurrentAccount(cl,accountID, sortCode, 0); 
    m.put(accountID, ca); 
} 
0

您的代码不编译,因为你尝试初始化绑定到String类型和帐户String类型的字符串的一个HashMap中的hasmap(键和值类型)

HashMap<String, CurrentAccount> accountsMap = new Hashmap<String, String>() 

应该是

HashMap<String, CurrentAccount> accountsMap = new Hashmap<String, CurrentAccount>() 

第一个参数是密钥值的类型,第二是找到你的HashMap中的值,可以使用下面的代码剪断

for (String key : accountsMap.keySet().iterator()) { 
     CurrentAccount current = accounts.get(key); 
} 

为重点

相关值的类型其中accountsMap是您的HashMap。

0

使用put(key, value);HashMap javadoc

m.put("SomeIdentifierString", ca); 

然后,每当你想访问特定对象。使用密钥来获得它

CurrentAccount account = m.get("SomeIdentifierString"); 

如果你想在整个地图迭代拿到钥匙和值,你可以做到这一点

for (Map.Entry<String, CurrentAccount> entry : m.entrySet()){ 
    String s = entry.getKey(); 
    CurrentAccount accuont = entry.getValue(); 
    // do something with them 
}