简体   繁体   English

搜索数组中的数据(列表)

[英]Searching data in a array(list)

I have a ArrayList containing Attributes 我有一个包含AttributesArrayList

class Attribute{
  private int id;
  public string getID(){
    return this.id;
  }

  private string value;
  public string getValue(){
    return this.value;
  }

  //... more properties here...
}

Well I filled the ArrayList with like hundreds of those attributes. 好吧,我用数百个这些属性填充了ArrayList。 And I want to find the Attribute with a defined ID. 我想找到具有已定义ID的属性。 I want to do something like this: 我想做这样的事情:

ArrayList<Attribute> arr = new ArrayList<Attribute>();
fillList(arr); //Method that puts a lot of these Attributes in the list
arr.find(234); //Find the attribute with the ID 234;

Is looping over the ArrayList the only solution. 遍历ArrayList是唯一的解决方案。

Well something's going to have to loop over the array list, yes. 好吧, 有些事情将不得不遍历数组列表,是的。 There are various ways of doing this, different libraries etc. 有多种方法可以执行此操作,也可以使用不同的库等。

If you fill the array in an ordered way (eg so that low IDs always come before high IDs) then you can perform a binary search in O(log N) time. 如果以有序方式填充数组(例如,使低ID始终位于高ID之前),则可以在O(log N)时间执行二进制搜索。 Otherwise, it'll be O(N). 否则,它将为O(N)。

If you're going to search by IDs a lot, however, why not create a Map<Integer, Attribute> to start with - eg a HashMap , or a LinkedHashMap if you want to preserve ordering? 但是,如果要按ID进行大量搜索,为什么不创建Map<Integer, Attribute>以-开头(例如, HashMapLinkedHashMap如果要保留顺序)呢?

If you're only going to search for a single ID (or a few), however, this almost certainly won't be worth it - there's a cost involved in hashing, after all; 但是,如果您只想搜索一个(或几个)ID,那几乎肯定是不值得的-毕竟,哈希涉及成本。 filling the map will be more expensive than filling the list, and the difference is likely to be greater than the time saved looking up a few IDs. 填写地图要比填写列表贵,而且差异可能大于查找几个ID所节省的时间。

Have you already established that this is a performance bottleneck? 您是否已经确定这是性能瓶颈? If so, this is an easy place to improve by using a map (or just a sorted list with a binary search). 如果是这样,这是通过使用地图(或只是带有二进制搜索的排序列表)来改进的简便位置。 If not, I wouldn't disturb your code if it more naturally uses a list than a map - but you should certainly check whether it's a bottleneck or not. 如果没有,如果它更自然地使用列表而不是地图,那么我不会打扰您的代码-但您一定要检查它是否是瓶颈。

您想使用地图

If you wish to access elements of a collection using element attributes, and this attribute is guaranteed to be unique per element, then you really should use a Map. 如果您希望使用元素属性访问集合中的元素,并且保证每个元素的此属性都是唯一的,那么您确实应该使用Map。 Try a Map with the Attribute.id as the key. 尝试使用Attribute.id作为键的Map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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