HashMap是一个适当的数据结构 [英] Is a HashMap a proper data structure

查看:146
本文介绍了HashMap是一个适当的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我存储在一个HashMap 3类对象中。

I store in a HashMap 3 types of object.

HashMap<String, ArrayList<Car>>

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

HashMap字符串键保留对象的类型(Car的子类),第二个元素在数组中存储有例如属性如:ID,日期等。

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. 如果没有提供有关其类型的信息,请检查HashMap中是否存在某个ID

  2. 打印给定类型的某个ID的元素。

  3. 打印某些类型的所有元素

  4. 如果每个对象分配了某个属性,则从集合(不同类型)中打印所有元素,其布尔值为true;

  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";

HashMap是否正确结构?如果谈到第一点,我觉得有问题。看来我将不得不遍历整个集合,如果有的话,其他的集合对于这样的要求会更好?

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?

推荐答案

方法是声音,但是由于您只想存储每个实例一次,所以 Set 是一个比 List 对于地图条目值:

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>>();

contains() HashSet 确实很快,所以发现如果你的地图包含一个特定的实例,它的价值不会太高。

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>();

这篇关于HashMap是一个适当的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆