Untitled

mail@pastecode.io avatar
unknown
java
a month ago
1.5 kB
1
Indexable
Never
import java.util.ArrayList;
import java.util.HashMap;

public class BigSearch {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        for(int index = 0; index <= 100000000L; index++){
            numbers.add(index);
        }

        int search = 43535;
        SearchNumberCache cache = SearchNumberCache.getInstance();
        
        long startTime = System.nanoTime();
        for(int index = 0; index <= 1000; index++){
            int result = cache.getIndex(numbers, search);
            System.out.println(result);
        }

        long endTime = System.nanoTime();
        System.out.println((endTime-startTime)/1e6 + "milliseconds" );
    }
}

class SearchNumberCache {
    private static SearchNumberCache instance;
    private HashMap<Integer, Integer> cache;

    private SearchNumberCache() {
        cache = new HashMap<>();
    }

    public static SearchNumberCache getInstance() {
        if (instance == null) {
            instance = new SearchNumberCache();
        }
        return instance;
    }

    public int getIndex(ArrayList<Integer> array, int keyword) {
        if (cache.containsKey(keyword)) {
            return cache.get(keyword);
        }

        int index = 0;
        for (Integer item : array) {
            if (item == keyword) {
                cache.put(keyword, index);
                return index;
            }
            index++;
        }
        cache.put(keyword, -1);
        return -1;
    }
}

Leave a Comment