Class SearchResultCache
java.lang.Object
com.university.bookstore.search.SearchResultCache
LRU (Least Recently Used) cache for search results.
Evicts least recently used items when the cache reaches its maximum size.
This implementation provides O(1) average time complexity for get and put operations by using a HashMap for O(1) lookups and a Deque for O(1) access order tracking.
- Since:
- 2024-09-15
- Version:
- 3.0
- Author:
- Navid Mohaghegh
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classStatistics class for cache performance monitoring. -
Constructor Summary
ConstructorsConstructorDescriptionSearchResultCache(int maxSize) Creates a new search result cache with the specified maximum size. -
Method Summary
Modifier and TypeMethodDescriptionvoidclear()Clears all entries from the cache.booleancontainsKey(String key) Checks if the cache contains results for the given key.Retrieves cached search results for the given key.intGets the maximum number of entries the cache can hold.getStats()Gets cache statistics including hit ratio and average age.booleanisEmpty()Checks if the cache is empty.booleanisFull()Checks if the cache is full.voidStores search results in the cache with the given key.booleanRemoves the entry with the given key from the cache.intsize()Gets the current number of entries in the cache.toString()
-
Constructor Details
-
SearchResultCache
public SearchResultCache(int maxSize) Creates a new search result cache with the specified maximum size.- Parameters:
maxSize- the maximum number of entries the cache can hold- Throws:
IllegalArgumentException- if maxSize is not positive
-
-
Method Details
-
get
-
put
Stores search results in the cache with the given key. Evicts the least recently used entry if the cache is full.- Parameters:
key- the cache keyresults- the search results to cache- Throws:
IllegalArgumentException- if key is null
-
containsKey
Checks if the cache contains results for the given key.- Parameters:
key- the cache key- Returns:
- true if the key exists in the cache
-
remove
Removes the entry with the given key from the cache.- Parameters:
key- the cache key to remove- Returns:
- true if an entry was removed, false if key not found
-
clear
public void clear()Clears all entries from the cache. -
size
public int size()Gets the current number of entries in the cache.- Returns:
- the cache size
-
getMaxSize
public int getMaxSize()Gets the maximum number of entries the cache can hold.- Returns:
- the maximum cache size
-
isEmpty
public boolean isEmpty()Checks if the cache is empty.- Returns:
- true if no entries are cached
-
isFull
public boolean isFull()Checks if the cache is full.- Returns:
- true if the cache has reached its maximum size
-
getStats
Gets cache statistics including hit ratio and average age.- Returns:
- cache statistics
-
toString
-