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.
values()
method in HashTable
?The values()
method of the HashTable
class returns the Collection
view of the values present in a HashTable
object.
public Collection<V> values()
This method doesn’t take an argument.
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);}}
In the code above:
In line 1, we imported the Hashtable
class.
In line 7, we created a HashTable
object with the name numbers
.
In lines 9 and 10, we used the put()
method to add two mappings ({1=one, 2=two}
) to the HashTable
object.
In line 13, we used the values()
method of HashTable
to get the values present in numbers
.
In line 16, we added a new entry (3, "Three"
) to the HashTable
object.
In line 17, we printed the values
variable. The newly added entry Three
will be automatically available in the values
variable without the need to call the values()
method because the previous call to the values()
method returned the Collection
view.