檢索自定義密鑰對象,這可能不是最好的數據結構,但我想知道是否有可能做到這一點: 我有一組工具,每一個唯一的ID和一堆或屬性。每個工具還有一個包含屬性的腔室集合。 我希望能夠使用該工具作爲HashMap和Chambers列表的鍵值。
當我從數據庫中取回所有腔室信息後,我想通過toolId獲取關鍵對象(工具),以便我可以將每個腔室添加到其合適的工具。我重寫了equals方法和hash方法以使用toolId。的Java從地圖
除了帶回所有的按鍵和迭代他們,看看他們是否等於toolId,是有一些方法來獲取密鑰對象
這是我到目前爲止的代碼:
Public class ToolBean {
Private String toolId;
Private String toolName;
Private String toolOwner;
Public ToolBean(String toolId){
this.toolId = toolId;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ToolBean other = (ToolBean) obj;
if (toolId == null) {
if (other.toolId != null)
return false;
} else if (!toolId.equals(other.toolId))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((toolId == null) ? 0 : toolId.hashCode());
return result;
}
}
我創建看起來像這樣的結構:
LinkedHashMap<ToolBean, LinkedHashMap<String, ChamberBean>> toolWithChamberMap = new LinkedHashMap<ToolBean, LinkedHashMap<String, ChamberBean>>();
我知道我可以創建一個ToolBean公頃結構通過Chambers的LinkedHashMap(LinkedHashMap),然後打開該工具,將新腔室添加到地圖中,將工具放回到原始地圖中。我想知道是否有辦法跳過這一步。
感謝, 布麗塔
只需用Key = toolid和Value = tool創建第二個HashMap。 – DaoWen
這看起來像足夠的代碼,允許你使用你的ToolBean類和散列圖。代碼對我來說看起來很不錯,假設你總是認爲兩個對象相同,如果他們有相同的工具ID。 –
無論如何你有什麼問題?代碼是否工作?我認爲會的。你試過了嗎?發生了什麼?道文的回答很好,但我認爲你不需要這樣做。使用添加到ToolBean的代碼,ToolBean對象可以合理地作爲哈希映射中的鍵。 –