Pengenalan Kelas Java.util.Hashtable

1. Gambaran keseluruhan

Hashtable adalah pelaksanaan tertua struktur data tabel hash di Java. The HashMap adalah pelaksanaan kedua, yang diperkenalkan pada JDK 1.2.

Kedua-dua kelas menyediakan fungsi yang serupa, tetapi terdapat juga perbezaan kecil, yang akan kami terangkan dalam tutorial ini.

2. Bilakah Menggunakan Hashtable

Katakan kita mempunyai kamus, di mana setiap perkataan mempunyai definisinya. Kita juga perlu mendapatkan, memasukkan dan membuang perkataan dari kamus dengan cepat.

Oleh itu, Hashtable (atau HashMap ) masuk akal. Kata-kata akan menjadi kunci dalam Hashtable , kerana ia seharusnya unik. Definisi, sebaliknya, akan menjadi nilai.

3. Contoh Penggunaan

Mari kita teruskan dengan contoh kamus. Kami akan memperagakan Word sebagai kunci:

public class Word { private String name; public Word(String name) { this.name = name; } // ... }

Katakan nilai adalah Strings . Sekarang kita boleh membuat Hashtable :

Hashtable table = new Hashtable();

Pertama, mari tambah entri:

Word word = new Word("cat"); table.put(word, "an animal");

Juga, untuk mendapatkan entri:

String definition = table.get(word);

Akhirnya, mari keluarkan entri:

definition = table.remove(word);

Terdapat banyak kaedah lagi di kelas, dan kami akan menerangkan beberapa kaedah kemudian.

Tetapi pertama, mari kita bincangkan beberapa syarat untuk objek utama.

4. Kepentingan hashCode ()

Untuk digunakan sebagai kunci dalam Hashtable , objek tidak boleh melanggar kontrak hashCode () . Ringkasnya, objek yang sama mesti mengembalikan kod yang sama. Untuk memahami mengapa mari kita lihat bagaimana jadual hash disusun.

Hashtable menggunakan tatasusunan. Setiap kedudukan dalam array adalah "baldi" yang boleh menjadi kosong atau mengandungi satu atau lebih pasangan nilai-kunci. Indeks setiap pasangan dikira.

Tetapi mengapa tidak menyimpan elemen secara berurutan, menambahkan elemen baru ke hujung array?

Intinya adalah bahawa mencari elemen mengikut indeks jauh lebih cepat daripada melakukan lelaran melalui elemen dengan perbandingan secara berurutan. Oleh itu, kita memerlukan fungsi yang memetakan kunci ke indeks.

4.1. Jadual Alamat Langsung

Contoh pemetaan yang paling mudah adalah jadual alamat langsung. Di sini kunci digunakan sebagai indeks:

index(k)=k, where k is a key

Kunci unik, iaitu setiap baldi mengandungi satu pasangan nilai-kunci. Teknik ini berfungsi dengan baik untuk kekunci integer apabila julatnya mungkin kecil.

Tetapi kita mempunyai dua masalah di sini:

  • Pertama, kunci kami bukan bilangan bulat, tetapi objek Word
  • Kedua, jika mereka bilangan bulat, tidak ada yang akan menjamin mereka kecil. Bayangkan bahawa kunci adalah 1, 2 dan 1000000. Kami akan mempunyai susunan besar 1000000 dengan hanya tiga elemen, dan selebihnya akan menjadi ruang terbuang

kaedah hashCode () menyelesaikan masalah pertama.

Logik untuk manipulasi data dalam Hashtable menyelesaikan masalah kedua.

Mari kita bincangkan ini secara mendalam.

4.2. Kodcincang () Menghubungi

Mana-mana objek Java mewarisi kaedah hashCode () yang mengembalikan nilai int . Nilai ini dikira dari alamat memori dalaman objek. Secara lalai hashCode () mengembalikan bilangan bulat yang berbeza untuk objek yang berbeza.

Oleh itu, objek utama boleh ditukar menjadi bilangan bulat menggunakan hashCode () . Tetapi bilangan bulat ini mungkin besar.

4.3. Mengurangkan Julat

kaedah get () , put () dan remove () mengandungi kod yang menyelesaikan masalah kedua - mengurangkan julat bilangan bulat yang mungkin.

Rumus mengira indeks untuk kunci:

int index = (hash & 0x7FFFFFFF) % tab.length;

Dimana tab.length adalah ukuran array, dan hash adalah nombor yang dikembalikan oleh kaedah hashCode () kunci .

Seperti yang kita lihat, indeks adalah peringatan hash pembahagian mengikut ukuran array . Perhatikan bahawa kod hash yang sama menghasilkan indeks yang sama.

4.4. Perlanggaran

Tambahan lagi, walaupun kod hash yang berbeza dapat menghasilkan indeks yang sama . Kami menyebutnya sebagai perlanggaran. Untuk menyelesaikan pertembungan Hashtable menyimpan LinkedList pasangan kunci-nilai.

Struktur data seperti itu disebut jadual hash dengan rantai.

4.5. Faktor beban

It is easy to guess that collisions slow down operations with elements. To get an entry it is not enough to know its index, but we need to go through the list and perform a comparison with each item.

Therefore it's important to reduce the number of collisions. The bigger is an array, the smaller is the chance of a collision. The load factor determines the balance between the array size and the performance. By default, it's 0.75 which means that the array size doubles when 75% of the buckets become not empty. This operation is executed by rehash() method.

But let's return to the keys.

4.6. Overriding equals() and hashCode()

When we put an entry into a Hashtable and get it out of it, we expect that the value can be obtained not only with same the instance of the key but also with an equal key:

Word word = new Word("cat"); table.put(word, "an animal"); String extracted = table.get(new Word("cat"));

To set the rules of equality, we override the key’s equals() method:

public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Word)) return false; Word word = (Word) o; return word.getName().equals(this.name); }

But if we don’t override hashCode() when overriding equals() then two equal keys may end up in the different buckets because Hashtable calculates the key’s index using its hash code.

Let’s take a close look at the above example. What happens if we don’t override hashCode()?

  • Two instances of Word are involved here – the first is for putting the entry and the second is for getting the entry. Although these instances are equal, their hashCode() method return different numbers
  • The index for each key is calculated by the formula from section 4.3. According to this formula, different hash codes may produce different indexes
  • This means that we put the entry into one bucket and then try to get it out from the other bucket. Such logic breaks Hashtable

Equal keys must return equal hash codes, that’s why we override the hashCode() method:

public int hashCode() { return name.hashCode(); }

Note that it's also recommended to make not equal keys return different hash codes, otherwise they end up in the same bucket. This will hit the performance, hence, losing some of the advantages of a Hashtable.

Also, note that we don’t care about the keys of String, Integer, Long or another wrapper type. Both equal() and hashCode() methods are already overridden in wrapper classes.

5. Iterating Hashtables

There are a few ways to iterate Hashtables. In this section well talk about them and explain some of the implications.

5.1. Fail Fast: Iteration

Fail-fast iteration means that if a Hashtable is modified after its Iterator is created, then the ConcurrentModificationException will be thrown. Let's demonstrate this.

First, we'll create a Hashtable and add entries to it:

Hashtable table = new Hashtable(); table.put(new Word("cat"), "an animal"); table.put(new Word("dog"), "another animal");

Second, we'll create an Iterator:

Iterator it = table.keySet().iterator();

And third, we'll modify the table:

table.remove(new Word("dog"));

Now if we try to iterate through the table, we'll get a ConcurrentModificationException:

while (it.hasNext()) { Word key = it.next(); }
java.util.ConcurrentModificationException at java.util.Hashtable$Enumerator.next(Hashtable.java:1378)

ConcurrentModificationException helps to find bugs and thus avoid unpredictable behavior, when, for example, one thread is iterating through the table, and another one is trying to modify it at the same time.

5.2. Not Fail Fast: Enumeration

Enumeration in a Hashtable is not fail-fast. Let's look at an example.

First, let's create a Hashtable and add entries to it:

Hashtable table = new Hashtable(); table.put(new Word("1"), "one"); table.put(new Word("2"), "two");

Second, let's create an Enumeration:

Enumeration enumKey = table.keys();

Third, let's modify the table:

table.remove(new Word("1"));

Now if we iterate through the table it won't throw an exception:

while (enumKey.hasMoreElements()) { Word key = enumKey.nextElement(); }

5.3. Unpredictable Iteration Order

Also, note that iteration order in a Hashtable is unpredictable and does not match the order in which the entries were added.

This is understandable as it calculates each index using the key's hash code. Moreover, rehashing takes place from time to time, rearranging the order of the data structure.

Hence, let's add some entries and check the output:

Hashtable table = new Hashtable(); table.put(new Word("1"), "one"); table.put(new Word("2"), "two"); // ... table.put(new Word("8"), "eight"); Iterator
    
      it = table.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = it.next(); // ... } }
    
five four three two one eight seven

6. Hashtable vs. HashMap

Hashtable and HashMap provide very similar functionality.

Both of them provide:

  • Fail-fast iteration
  • Unpredictable iteration order

But there are some differences too:

  • HashMap doesn't provide any Enumeration, while Hashtable provides not fail-fast Enumeration
  • Hashtable doesn't allow null keys and null values, while HashMap do allow one null key and any number of null values
  • Hashtable‘s methods are synchronized while HashMaps‘s methods are not

7. Hashtable API in Java 8

Java 8 has introduced new methods which help make our code cleaner. In particular, we can get rid of some if blocks. Let's demonstrate this.

7.1. getOrDefault()

Let's say we need to get the definition of the word “dogand assign it to the variable if it is on the table. Otherwise, assign “not found” to the variable.

Before Java 8:

Word key = new Word("dog"); String definition; if (table.containsKey(key)) { definition = table.get(key); } else { definition = "not found"; }

After Java 8:

definition = table.getOrDefault(key, "not found");

7.2. putIfAbsent()

Let's say we need to put a word “cat only if it's not in the dictionary yet.

Before Java 8:

if (!table.containsKey(new Word("cat"))) { table.put(new Word("cat"), definition); }

After Java 8:

table.putIfAbsent(new Word("cat"), definition);

7.3. boolean remove()

Let's say we need to remove the word “cat” but only if it's definition is “an animal”.

Before Java 8:

if (table.get(new Word("cat")).equals("an animal")) { table.remove(new Word("cat")); }

After Java 8:

boolean result = table.remove(new Word("cat"), "an animal");

Finally, while old remove() method returns the value, the new method returns boolean.

7.4. replace()

Let's say we need to replace a definition of “cat”, but only if its old definition is “a small domesticated carnivorous mammal”.

Before Java 8:

if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) { table.put(new Word("cat"), definition); }

After Java 8:

table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition);

7.5. computeIfAbsent()

This method is similar to putIfabsent(). But putIfabsent() takes the value directly, and computeIfAbsent() takes a mapping function. It calculates the value only after it checks the key, and this is more efficient, especially if the value is difficult to obtain.

table.computeIfAbsent(new Word("cat"), key -> "an animal");

Hence, the above line is equivalent to:

if (!table.containsKey(cat)) { String definition = "an animal"; // note that calculations take place inside if block table.put(new Word("cat"), definition); }

7.6. computeIfPresent()

This method is similar to the replace() method. But, again, replace() takes the value directly, and computeIfPresent() takes a mapping function. It calculates the value inside of the if block, that's why it's more efficient.

Let's say we need to change the definition:

table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value);

Hence, the above line is equivalent to:

if (table.containsKey(cat)) { String concatination=cat.getName() + " - " + table.get(cat); table.put(cat, concatination); }

7.7. compute()

Now we'll solve another task. Let's say we have an array of String, where the elements are not unique. Also, let's calculate how many occurrences of a String we can get in the array. Here is the array:

String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };

Also, we want to create a Hashtable which contains an animal as a key and the number of its occurrences as a value.

Here is a solution:

Hashtable table = new Hashtable(); for (String animal : animals) { table.compute(animal, (key, value) -> (value == null ? 1 : value + 1)); }

Finally, let's make sure, that the table contains two cats, two dogs, one bird and two mouses:

assertThat(table.values(), hasItems(2, 2, 2, 1));

7.8. merge()

There is another way to solve the above task:

for (String animal : animals) { table.merge(animal, 1, (oldValue, value) -> (oldValue + value)); }

The second argument, 1, is the value which is mapped to the key if the key is not yet on the table. If the key is already in the table, then we calculate it as oldValue+1.

7.9. foreach()

This is a new way to iterate through the entries. Let's print all the entries:

table.forEach((k, v) -> System.out.println(k.getName() + " - " + v)

7.10. replaceAll()

Additionally, we can replace all the values without iteration:

table.replaceAll((k, v) -> k.getName() + " - " + v);

8. Conclusion

In this article, we've described the purpose of the hash table structure and showed how to complicate a direct-address table structure to get it.

Selain itu, kami telah merangkumi perlanggaran dan faktor beban dalam Hashtable. Juga, kita telah mengetahui sebab untuk mengatasi sama dengan () dan hashCode () untuk objek utama.

Akhirnya, kami telah membincangkan sifat Hashtable dan Java 8 khusus API.

Seperti biasa, kod sumber lengkap terdapat di Github.