Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searchable list of objects in Java

Tags:

java

list

search

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?

like image 398
Christian Avatar asked Mar 26 '10 14:03

Christian


3 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.

like image 138
Etienne de Martel Avatar answered Oct 20 '22 21:10

Etienne de Martel


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;
    }
like image 36
Shervin Asgari Avatar answered Oct 20 '22 19:10

Shervin Asgari


Wouldn't you use TreeMap instead of List using the ID as your Key?

like image 2
Mike Cornell Avatar answered Oct 20 '22 21:10

Mike Cornell