简体   繁体   English

可搜索的Java对象列表

[英]Searchable list of objects in Java

I want to create a large (~300,000 entries) List of self defined objects of the class Drug . 我想创建一个大型(~300,000个条目)的Drug类自定义对象列表。 Every Drug has an ID and I want to be able to search the Drugs in logarithmic time via that ID. 每种药物都有一个ID,我希望能够通过该ID在对数时间内搜索药物。 What kind of List do I have to use? 我必须使用什么样的清单? How do I declare that it should be searchable via the ID? 我如何声明它应该可以通过ID搜索?

The various implementations of the Map interface should do what you want. Map接口的各种实现应该做你想要的。

Just remember to override the hashCode() method of your Drug class if you plan to use a HashMap. 如果您打算使用HashMap,请记住覆盖Drug类的hashCode()方法。

public class Drug implements Comparable<Drug> {

    public int compareTo(Drug o) {
         return this.id.compareTo(o.getId());
    }
}

Then in your List you can use binarySearch 然后在列表中,您可以使用binarySearch

    List<Drug> drugList; <--- List of all drugs
    Drug drugToSearchFor; <---- The drug that you want to search for, containing the id
    // Sort before search
    Collections.sort(drugList);
    int index = Collections.binarySearch(drugList, drugToSearchFor);

    if (index >= 0) {
        return true;
    } else {
        return false;
    }

使用ID作为密钥,您不会使用TreeMap而不是List吗?

If searching by a key is important for you, then you probably need to use a Map and not a List. 如果按键搜索对您很重要,那么您可能需要使用Map而不是List。 From the Java Collections Trail : 来自Java Collections Trail

The three general-purpose Map implementations are HashMap, TreeMap and LinkedHashMap. 三个通用Map实现是HashMap,TreeMap和LinkedHashMap。 If you need SortedMap operations or key-ordered Collection-view iteration, use TreeMap; 如果需要SortedMap操作或按键排序的Collection-view迭代,请使用TreeMap; if you want maximum speed and don't care about iteration order, use HashMap; 如果您想要最大速度而不关心迭代顺序,请使用HashMap; if you want near-HashMap performance and insertion-order iteration, use LinkedHashMap. 如果您想要近HashMap性能和插入顺序迭代,请使用LinkedHashMap。

Due to the high number of entries you might consider to use a database instead of holding everything in memory. 由于条目数量很多,您可能会考虑使用数据库而不是将所有内容保存在内存中。

If you still want to keep it in memory you might have a look at b-trees. 如果你仍然希望将它保存在内存中,你可能会看看b-trees。

You could use any list, and as long as it is sorted you can use a binary search . 您可以使用任何列表,只要它已排序,您就可以使用二进制搜索 But I would use a Map which searches in O(1). 但我会使用在O(1)中搜索的Map。

我知道我对这个陈述非常多余,但是正如大家所说的那样,这不是地图的情况吗?

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

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