需要找出" key"在java中的数据结构

时间:2014-08-08 02:40:31

标签: java data-structures collections

我正在寻找一个数据结构,我需要存储值,然后根据key检索它。但在我的情况下,我的键和值将是相同的,所以我不能使用HashMap。 HashSet也没用,因为在这种情况下我需要进行顺序搜索才能找到我的密钥。 所以这是我正在寻找的例子:

class A{
   int x;
   int y;
   int z;

   equals(){
     //equals is overridden based only on int x and int y; and not on z.
   }
}

Class B{
  Map<A,z>mapA = new HasMap<>(A,z); - option 1 , not useful.
  //store values in mapA. my z is dummy, in fact I need only class A object on some condition match.

  fun(object k){
     if(mapA.containsValue(k))
     {
        /*here I need to get class object A if it matches with "k". There is no function available in map to get the key if it matches key. Also if I use HashSet, in that case I need to retrieve the value by iterating over the set which is not preferable. I wanted to achieve this search in O(1) or O(logn) */
     }
  }
}

任何建议都将受到高度赞赏。

Edit1: Hashset只会告知密钥是否存在于集合中?它没有给我钥匙。要获得Key,我必须遍历该集合。如果我错了,请纠正我。

2 个答案:

答案 0 :(得分:5)

如果键是值,则HashSet正是您所需要的。搜索密钥将花费O(1)预期时间,与任何哈希表相同。

答案 1 :(得分:0)

在这种情况下,我们可以使用HashMap与<key,key>代替<key,value>。这将帮助我使用键作为值从地图中获取键。在我的情况下,我需要一些东西,以便我们可以在没有任何迭代的情况下在单个操作中获取值。虽然地图可以做到但是通过设计它应该是用两个值来表达,即键和值。除了MAP之外,java中没有其他数据结构可以做到这一点。