Create LRUcache

LRU algorithm class:

 import java.util.LinkedHashMap; import java.util.Map; public class LRUAlgoritm<K, V> implements Cache<K, V> { private final LRUStorage storage;//Π½Π΅ Ρ…ΠΎΡ‡Π΅Ρ‚ компилится Ρ‚.ΠΊ."The blank final //field storage may not have been initialized" // ΠΏΠΎΠΌΠΎΠ³ΠΈΡ‚Π΅ ΠΊΠ°ΠΊ здСсь ΠΏΡ€Π°Π²ΠΈΠ»ΡŒΠ½ΠΎ Ρ€Π΅Π°Π»ΠΈΠ·ΠΎΠ²Π°Ρ‚ΡŒ @Override public V get(K key) { return storage.get(key); } @Override public V put(K key, V value) { return storage.put(key, value); } private class LRUStorage extends LinkedHashMap<K, V> { private final int capacity; private LRUStorage(int capacity) { this.capacity = capacity; } protected boolean removedEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } } } 

Cache interface is simple:

 public interface Cache <K,V>{ V get (K key); V put (K key, V value); } 

in runner class

 public class Runner { public static void main (String[] args){ LRUAlgoritm<String, String> lruAlgoritm = new LRUAlgoritm<>(); lruAlgoritm.put("1","1"); } } 

trying to create cache overload and can't

  1. The compiler requires the LRUalgoritm class LRUalgoritm initialize the storage constant. How does it need to be initialized here?
  2. How to apply to the object of class LRUStorage , that would set my capacity

    1 answer 1

    The compiler says that it is necessary to initialize the class field explicitly. This can be done in one of the following ways:

    • in class constructor
    • adding simple initialization when creating a class object

    For example:

     public class LRUAlgoritm<K, V> implements Cache<K, V> { private final LRUStorage<K,V> storage = new LRUStorage<>(10); // Явная инициализация с установкой capacity // ΠšΠΎΠ½ΡΡ‚Ρ€ΡƒΡ‚ΠΎΡ€ public LRUAlgoritm(int capacity) { this.storage = new LRUStorage<>(capacity); } } 
    • added public class LRUAlgoritm<K, V> implements Cache<K, V>{ private final LRUStorage storage = new LRUStorage<>(); public LRUAlgoritm(LRUStorage<K, V> storage) { this.storage = storage; } public class LRUAlgoritm<K, V> implements Cache<K, V>{ private final LRUStorage storage = new LRUStorage<>(); public LRUAlgoritm(LRUStorage<K, V> storage) { this.storage = storage; } public class LRUAlgoritm<K, V> implements Cache<K, V>{ private final LRUStorage storage = new LRUStorage<>(); public LRUAlgoritm(LRUStorage<K, V> storage) { this.storage = storage; } - Sergei
    • @Sergei changed the answer. It is necessary to choose only one way, both will not be immediately activated. To set the capacity it must be specified when creating the object LRUStorage - Yuri Heiko
    • installation capacity occurs runner - Sergei
    • In general, you obviously should read about programming in Java, in particular, what a class is and how to use it - Yuri Heiko
    • @Sergei once again changed the answer - Yuri Heiko