I want to create a large (~300,000 entries) List of self defined objects of the class Drug.
Every Drug has an ID and I want to be able to search the Drugs in logarithmic time via that ID.
What kind of List do I have to use?
How do I declare that it should be searchable via the ID?
-
1What is the range of the IDs?Michael Myers– Michael Myers ♦2010-03-26 14:21:03 +00:00Commented Mar 26, 2010 at 14:21
-
1Any chance to put them in a DB and let it do the work with help of SQL/JDBC? This is undoubtely going to be more fast and efficient.BalusC– BalusC2010-03-26 14:21:30 +00:00Commented Mar 26, 2010 at 14:21
-
@BalusC only if the data is not changing too much. If he has to update everything in short intervals and persistence is not needed, then a DB won't make much sense. But my first thoughts are pointing towards a DB too.Patrick Cornelissen– Patrick Cornelissen2010-03-26 14:35:01 +00:00Commented Mar 26, 2010 at 14:35
7 Answers
The various implementations of the Map interface should do what you want.
Just remember to override the hashCode() method of your Drug class if you plan to use a HashMap.
8 Comments
hashCode and equals only if you want to use your class as the key of a Map or if you want to put it in a Set. If you simply want to use it as the value of a Map then you don't need to implement them. Also: If you implement equals(), then you must implement hashCode() as well.equals(Object) and hashCode() methods.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
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;
}
Comments
Wouldn't you use TreeMap instead of List using the ID as your Key?
5 Comments
If searching by a key is important for you, then you probably need to use a Map and not a List. From the Java Collections Trail:
The three general-purpose Map implementations are HashMap, TreeMap and LinkedHashMap. If you need SortedMap operations or key-ordered Collection-view iteration, use TreeMap; if you want maximum speed and don't care about iteration order, use HashMap; if you want near-HashMap performance and insertion-order iteration, use LinkedHashMap.
Comments
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).