What is the Hashtable.values() method in Java?
A hash table is a collection of key-value pairs. The object to be used as a key should implement the hashCode and equals methods, and the key and the value should not be null.
You can read the difference between HashTable and HashMap here.
What is the values() method in HashTable?
The values() method of the HashTable class returns the Collection view of the values present in a HashTable object.
Syntax
public Collection<V> values()
This method doesn’t take an argument.
Code
The following code demonstrates how to use the values() method.
import java.util.Hashtable;import java.util.Collection;class ValuesExample {public static void main(String[] args) {// create a HashtableHashtable<Integer, String> numbers = new Hashtable<>();numbers.put(1, "One");numbers.put(2, "Two");System.out.println("The Hashtable is - " + numbers);Collection<String> values = numbers.values();System.out.println("The values in Hashtable is - " + values);numbers.put(3, "Three");System.out.println("The values in Hashtable is - " + values);}}
Explanation
In the code above:
-
In line 1, we imported the
Hashtableclass. -
In line 7, we created a
HashTableobject with the namenumbers. -
In lines 9 and 10, we used the
put()method to add two mappings ({1=one, 2=two}) to theHashTableobject. -
In line 13, we used the
values()method ofHashTableto get the values present innumbers. -
In line 16, we added a new entry (
3, "Three") to theHashTableobject. -
In line 17, we printed the
valuesvariable. The newly added entryThreewill be automatically available in thevaluesvariable without the need to call thevalues()method because the previous call to thevalues()method returned theCollectionview.