The most detailed explanation in the history of java collection classes – HashTable, Properties

The most detailed explanation in the history of java [collection] classes – HashTable, Properties

1. Basic introduction

  • HashTableNeither the key nor the value can be empty, otherwise an exception will be thrown
  • The method of use is basically the HashMapsame
  • HashTablethread-safe, HashMapthread-unsafe

2. HashTable bottom layer

Code first:

Hashtable hashtable = new Hashtable();
hashtable.put("john",100);
hashtable.put("tom",250);
hashtable.put("tom",1314);
System.out.println(hashtable);
------------------------
output:
{tom=1314, john=100}

Enter putthe method first, you can see whether it is empty at the putfront of the method value, and if it is empty, an exception is thrown directly

if (value == null) {
    throw new NullPointerException();
}

Similarly, HashTablethere are also replacement mechanisms and expansion mechanisms! 🎈

3. HashTable expansion mechanism

HashTableHas its own expansion mechanism, which is different from HashSetandHashMap

First of all, we need to understand that when HashTableadding key-value pairs, what really adds is the following method:

addEntry(hash, key, value, index);

Let’s take a look at his true face:

private void addEntry(int hash, K key, V value, int index) {
    Entry<?,?> tab[] = table;
    if (count >= threshold) {
        // Rehash the table if the threshold is exceeded
        rehash();

        tab = table;
        hash = key.hashCode();
        index = (hash & 0x7FFFFFFF) % tab.length;
    }

    // Creates the new entry.
    @SuppressWarnings("unchecked")
    Entry<K,V> e = (Entry<K,V>) tab[index];
    tab[index] = new Entry<>(hash, key, value, e);
    count++;
    modCount++;
}

When the number of added elements is greater than the critical value, execute the rehashmethod (this method is the real expansion method)

if (count >= threshold) {
    // Rehash the table if the threshold is exceeded
    rehash();
    tab = table;
    hash = key.hashCode();
    index = (hash & 0x7FFFFFFF) % tab.length;
}

Continue to chase into the rehashmethod:

protected void rehash() {
    int oldCapacity = table.length;
    Entry<?,?>[] oldMap = table;

    // overflow-conscious code
    int newCapacity = (oldCapacity << 1) + 1;
    if (newCapacity - MAX_ARRAY_SIZE > 0) {
        if (oldCapacity == MAX_ARRAY_SIZE)
            // Keep running with MAX_ARRAY_SIZE buckets
            return;
        newCapacity = MAX_ARRAY_SIZE;
    }
    Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

    modCount++;
    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    table = newMap;

    for (int i = oldCapacity ; i-- > 0 ;) {
        for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
            Entry<K,V> e = old;
            old = old.next;

            int index = (e.hash & 0x7FFFFFFF) % newCapacity;
            e.next = (Entry<K,V>)newMap[index];
            newMap[index] = e;
        }
    }
}

Don’t panic, let’s analyze this expansion method

First, get the old capacity:

int oldCapacity = table.length;

int newCapacity = (oldCapacity << 1) + 1;

Continue down to the actual scaling code:

Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

4. Comparison of HashMap and HashTable

5.[Properties]

PropertiesinheritHashTable

Generally used for operational configuration file writing

Example of use:

import java.util.Properties;

/**
 * Properties demo
 */
public class PropertiesText {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("john",521);
        properties.put("tom",1314);
        properties.put("tom",100);System.out .println(properties);
         // Get the value by key 
        System. 
        out .println ( properties. get ( "tom" ));
         // delete 
        properties. remove ( "tom" );
        System.out.println(properties);
    }
}
------------------------------
output:
{tom=100, john=521}
{john=521}

6. Collection selection rules 🙌

Store an array of objects:Collection

  • Duplicates are allowed, multiple selections are added and deleted, and multiple selections are LinkedListchanged.ArrayList
  • Do not allow duplicates, unordered selection HashSet, sorted selection TreeSet, consistent selection of insertion and removal orderLinkedHashSet

Store key-value pairs:Map

  • Unordered keys:HashMap
  • Sort by keys:TreeMap
  • The keys are inserted and removed in the same order:LinkedHashMap
  • Read file:Properties

Leave a Comment

Your email address will not be published. Required fields are marked *