Example #1
0
        public void Add(TKey key, TValue value)
        {
            if (linkedDictionary.ContainsKey(key))
            {
                throw new ArgumentException("An item with the same key has already been added");
            }

            linkedDictionary.Add(key, value);
        }
Example #2
0
        public void Add(TKey key, TValue value)
        {
            if (dictionary.ContainsKey(key))
            {
                throw new ArgumentException("An item with the same key has already been added");
            }

            if (dictionary.Count == capacity)
            {
                Shrink();
            }

            LinkedDictionary <TKey, ValueWrapper> dict = GetDictByFrequency(0);
            ValueWrapper wrapper = new ValueWrapper(value, 0);

            dict.Add(key, wrapper);
            dictionary[key] = wrapper;
            lowestFrequency = 0;
        }
Example #3
0
        public bool TryGetValue(TKey key, out TValue value)
        {
            ValueWrapper wrapper = default;

            if (dictionary.TryGetValue(key, out wrapper))
            {
                int currentFrequency = wrapper.frequency;
                if (currentFrequency < maxFrequency)
                {
                    int nextFrequency = currentFrequency + 1;

                    LinkedDictionary <TKey, ValueWrapper> curDict  = GetDictByFrequency(currentFrequency);
                    LinkedDictionary <TKey, ValueWrapper> nextDict = GetDictByFrequency(nextFrequency);

                    curDict.Remove(key);
                    nextDict.Add(key, wrapper);
                    wrapper.frequency = nextFrequency;

                    dictionary[key] = wrapper;
                    if (lowestFrequency == currentFrequency && curDict.Count == 0)
                    {
                        lowestFrequency = nextFrequency;
                    }
                }
                else
                {
                    // f相同时 用LRU策略
                    LinkedDictionary <TKey, ValueWrapper> dict = GetDictByFrequency(currentFrequency);
                    dict.Remove(key);
                    dict.Add(key, wrapper);
                }
                value = wrapper.value;
                return(true);
            }
            else
            {
                value = default;
                return(false);
            }
        }