SimpleHashTable

1951 ワード

簡単なHash Table実現は、次回聞かれると、少なくとも0からではありません.しかし、これはあまり多くありません.
    public struct Item<K, V>
    {
        public K Key { get; set; }

        public V Value { get; set; }
    }

    public class SimpleHashTable<K, V>
    {
        private int _size;

        private LinkedList<Item<K, V>>[] _items;

        public SimpleHashTable(int size)
        {
            this._size = size;
            _items = new LinkedList<Item<K, V>>[_size];
        }

        public void Add(K key, V value)
        {
            var item = Find(key);
            if (item == null)
            {
                var list = FindListByKey(key);
                list.AddLast(new Item<K, V>()
                {
                    Key = key,
                    Value = value
                });
            }
            else
            {
                throw new Exception("The item is already exist.");
            }
        }

        public V Find(K key)
        {
            var list = FindListByKey(key);
            foreach (var item in list)
            {
                if (item.Key.Equals(key))
                {
                    return item.Value;
                }
            }

            return default(V);
        }

        public void Remove(K key)
        {
            var list = FindListByKey(key);
            var item = list.Where(a => a.Key.Equals(key)).FirstOrDefault();
            if (!item.Equals(default(Item<K, V>)))
            {
                list.Remove(item);
            }
        }

        private LinkedList<Item<K, V>> FindListByKey(K key)
        {
            var hash = key.GetHashCode();
            var index = Math.Abs(hash % _size);

            if (_items[index] == null)
            {
                _items[index] = new LinkedList<Item<K, V>>();
            }

            return _items[index];
        }
    }