简体   繁体   中英

need to find out “key” in data structure in java

I am looking for a data structure where I need to store values and then to retrieve it based on key.But in my case my key and value will be same, so I can't use HashMap. HashSet is also not useful because in that case I need to do a sequential searching to find my key. so here is the example of what I am looking:

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) */
     }
  }
}

Any suggestions will be highly appreciated.

Edit1: Hashset only tells whether key is present in collection or not ? it doesn't give me the key. To get Key I have to iterate through the collection.Please correct me if I am wrong.

If the key is the value, HashSet is exactly what you need. Searching the key would take O(1) expected time, the same as any hash table.

We can use HashMap with <key,key> instead of <key,value> in this case. This will help me in getting the key from the map using the key as value.In my case I was needing something so that we can get a value in a single operation without any iteration.Though map can do that but by design it is supposed to act with two values ie key and value. Apart from MAP there is no other data structure in java which can do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM