【问题标题】:Java retrieving a custom key object from a mapJava 从地图中检索自定义键对象
【发布时间】:2013-08-19 19:43:36
【问题描述】:

这可能不是最好的数据结构,但我想知道是否可以这样做: 我有一组工具,每个工具都有一个唯一的 ID 和一堆或属性。每个工具还有一个包含属性的房间集合。 我希望使用该工具作为 HashMap 的键和分庭列表作为值。
从数据库中取回所有腔室信息后,我想通过 toolId 获取关键对象(工具),以便将每个腔室添加到相应的工具中。我重写了equals方法和hash方法来使用toolId。

除了带回所有键并对其进行迭代以查看它们是否等于 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>>();

我知道我可以使用具有 Chambers 的 LinkedHashMap (LinkedHashMap) 的 ToolBean 创建一个结构,然后打开工具,将新的房间添加到地图中,然后将工具放回原始地图中。我想知道是否有办法跳过这一步。

谢谢, 布里塔

【问题讨论】:

  • 只需使用 Key=toolid 和 Value=tool 创建第二个 HashMap。
  • 这看起来足以让您使用带有哈希映射的 ToolBean 类。代码对我来说看起来不错,假设您总是认为两个对象相同,如果它们具有相同的工具 id。
  • 那么你的问题是什么?代码会起作用吗?我认为会的。你试过了吗?发生了什么?道文的回答很好,但我认为你不需要这样做。使用您添加到 ToolBean 的代码,ToolBean 对象可以合理地充当哈希映射中的键。
  • 所以问题是:我有一个来自数据库的房间对象,需要使用 toolId = 'aaa' 将其添加到工具中 如何获取/添加值到键? getKey('aaa') 会起作用还是我需要获取对象?
  • 这可能不清楚,但是带有 toolId 'aaa' 的 ToolObject 已经有腔室 'one',我需要将腔室 'two' 添加到腔室地图中。 Can (How Can) 我使用 ToolObject 作为键来做到这一点。

标签: java hashmap linkedhashmap


【解决方案1】:

假设

class ToolBean { 
    // as described in OP
}

class Chamber {
    // some opaque class
}

你的要求似乎是这样的:

// Master map of ToolBean to map of Chamber objects
Map<ToolBean, Map<String, Chamber>> toolBeanToChamberMap = 
    new LinkedHashMap<ToolBean,Map<String,Chamber>>();

// A tool bean and a chamber
ToolBean tb1 = new ToolBean(...);
Chamber  ch1 = new Chamber(...);

// Create a map that will contain Chambers and their String keys
Map<String,Chamber> chMap = new LinkedHashMap<String,Chamber>();

// Put the Chamber into this map
chMap.put("one",ch1);

// Put the map of Chambers into the master map, keyed off the ToolBean
toolBeanToChamberMap.put(tb1, chMap);

// sometime later ...

ToolBean tb2 = ... // may be the same as tb1

// A new Chamber to be added to the data structure
Chamber ch2 = new Chamber(...);

// First find the Chamber map in the master map, matching the ToolBean of interest
Map<String,Chamber> temp = toolBeanToChamberMap.get(tb2);

// 'temp' is a reference to the submap - if it's null, this ToolBean wasn't in the master map yet
if (temp == null) {
    // So create a new empty submap
    temp = new LinkedHashMap<String,Chamber>();
    // Add it to the master map
    toolBeanToChamberMap.put(tb2,temp);
}
// At this point 'temp' is either the pre-existing submap or the one we just added
temp.put("two",ch2);

然而,除非你有充分的理由这样做,否则我建议如下:

public class ToolBean {
    some attributes...
    Map<String, Chamber> chamberMap = new LinkedHashmap<String,Chamber>();
    ...
    public void addChamber(String name, Chamber c) {
        // similar logic as above
    }
    public Chamber getChamber(String name) {
        return chamberMap.get(name);
    }
}

Set<ToolBean> toolBeans = new HashSet<ToolBean>();

ToolBean tb1 = new ToolBean();
tb1.addChamber("one", new Chamber(...));
tb1.addChamber("two", new Chamber(...));
toolBeans.add(tb1);

换句话说,将房间地图的所有复杂性隐藏在ToolBean 类中。

处理重复的 Chamber 值和空值,留作练习。

【讨论】:

  • 创建第一个 ToolBean 并将其放入地图后,如何获取并添加回房间地图。如果我的第一个键 (ToolBean) 是 toolId='aaa' 的工具,并且房间地图有房间“一”,我想添加房间“二”。会不会像 ChamberMap = toolWithChamberMap('aaa') ChamberMap.put('one', Chamber) ?我知道我可以像 Nikita 建议的那样做,但我想看看我是否可以将 ToolBean 作为关键。
  • 啊。不清楚您是否要使用房间地图作为键来查找 ToolBean 实例。那完全是一个不同的问题,我的回答不适用。 Chamber 对象的定义是什么? toolWithChamberMap("aaa") 返回什么? "aaa" 如何引用 Chamber 对象?您确实没有提供足够的信息。
  • 很抱歉我解释得太差了。第一个对象 Key1 = ToolBean { toolId = ‘tool1’;工具名 = 'name1'; toolData='someData";} Value1 = ChamberMap1 {'one', Chamber1} 我需要修改 ChamberMap1 以添加腔室“二”。我怎么做? /n 我可以使用tooId和equals函数吗,还是需要创建整个对象来获取房间地图?
  • 吉姆,非常完美。结构很好的答案,正是我需要知道的。我希望我有足够的积分来支持它。谢谢。布里塔
【解决方案2】:

我个人会创建 2 个地图:ToolId -> ToolBean 和 ToolId -> Chambers。它类似于您的方法,但我不喜欢 ToolBean 成为地图中的关键。我没有看到 ToolBean 作为键有太多好处,而且它还会使代码复杂化,因为您需要覆盖忽略名称和所有者的 equals 和 hashcode 方法。

第二种方法是将房间嵌入到 ToolBean 本身。

使用您的代码的第三种方法是:拥有 ToolId,您可以使用此 id 创建 ToolBean 的实例,并将其用作检索房间地图的键。就我个人而言,这对我来说就像是 hack。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多