Is a HashMap a proper data structure

2020-05-02 02:52发布

问题:

I store in a HashMap 3 types of object.

HashMap<String, ArrayList<Car>>

['Lorry', [list of lorries]]
['Sport', [list of sport's cars]]

The HashMap string key keeps the type of object (a subclass of Car), the second element stores in array the objects that have e.g. attributes like: ID, date etc.

The four main things I have to do are:

  1. Check if certain ID exist in HashMap when there is no information provided about its type
  2. Print elements of certain ID given the type.
  3. Print all elements of certain type
  4. Print all element from the collection (of different types) if certain attribute that each object has assigned has a Boolean value of e.g. "true";

Is the HashMap the proper structure? I find it problematic if it comes to the first point. It seems like I will have to traverse the whole collection and if so what other collection is better for such requirements?

回答1:

The basic approach is sound, however since you only want to store each instance once, a Set is a better choice than a List for the map entry value:

Map<String, Set<Car>> typeCache = new HashMap<String, HashSet<Car>>();

The contains() method of HashSet is very fast indeed, so finding if your map contains a particular instance in it values is not going to cost much.

Using two maps would probably be better though - once for each type of lookup, so also use:

Map<String, Object> idCache = new HashMap<String, Object>();


回答2:

A HashMap is the right data structure for the job, but in your case you might consider using two HashMaps: One holding the relation 'Car Type' -> 'Cars of that Type', and a second one for the relation 'ID' -> 'Car with that ID'.