Domanda

Suppose you have a list of Sunglasses objects where there are ...

  1. 4 attributes, color, shape, style and brand.
  2. no identical ones; the combination of 4 attributes always different

What is the fastest way to retrieve them?

I think:

  1. Override the hashcode() method in the Sunglasses class (should be unique because none of them are identical).
  2. Then using each object's hashcode as key, object itself as value, put them into a Hashmap

Suppose I remember exactly what color shape and style and brand of a glass I want to get,

  1. I apply them with the hashcode method I have implemented.
  2. then get it from the hashmap, this should give me contants time O(1) retrieval.

Problem is what if I only know the color. How do I get a list of all glasses with the same color?

È stato utile?

Soluzione

Build a HashMap<Color,Collection<Glasses>> in addition to your other data structures.

This map essentially servers as an index on the Color attribute.

Whenever you add or remove glasses from your other data structures, make sure to update this color index as well.

Altri suggerimenti

  1. Create a value class to hold the 4 attributes, and create hashcode and equals methods that use all the fields.
  2. Use the class as a field of sunglasses instead of having separate fields (that way if you change it to add another field, it changes everywhere)
  3. Use a hash map of value class --> sunglasses and when querying, build a value object at use map.get(value)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top