Hashtable
类实现将键映射到值的哈希表。 Hashtable类不允许null作为键或值。用作Hashtable类的键的对象必须实现hashCode
方法和equals
方法。
Hashtable中使用的基本方法是:
put()
– 将新元素(键值)添加到Hashtable中。get()
– 通过传递键返回值。remove()
– 从Hashtable中删除键和值。size()
– 返回Hashtable的大小。containsKey()
– 如果密钥存在于Hashtable中则返回true,否则返回false。containsValue()
– 如果Hashtable中存在值,则返回true,否则返回false。clear()
– 从Hashtable中删除所有元素。
文件:HashTableExample.java –
package com.yiibai.tutorial; import java.util.Hashtable; /** * @author yiibai * */ public class HashTableExample { public static void main(String[] args) { Hashtable<String String> hashtable=new Hashtable<>(); /*Adding key and values in Hashtable*/ hashtable.put("1" "One"); hashtable.put("2" "Two"); hashtable.put("3""Three"); hashtable.put("4" "Four"); hashtable.put("5" "Five"); System.out.println("Hashtable key-values are:"+hashtable); /*Get value by key from the Hashtable*/ System.out.println("Value of '4' is: "+hashtable.get("4")); /*Removing key and value from the Hashtable */ hashtable.remove("4"); System.out.println("After removal Hashtable Key-Value: " +hashtable); /*Getting size of Hashtable*/ System.out.println("Size of Hashtable is : "+hashtable.size()); /*Checking if key exist in the Hashtable or not*/ System.out.println("Key '3' exist: "+hashtable.containsKey("3")); /*Checking if value exist in the Hashtable or not*/ System.out.println("Key '6' exist: "+hashtable.containsValue("6")); /*Remove all keys and values from the Hashtable*/ hashtable.clear(); System.out.println("After clearing Hashtable: "+hashtable); } }
执行上面示例代码,得到以下结果:
Hashtable key-values are:{5=Five 4=Four 3=Three 2=Two 1=One} Value of '4' is: Four After removal Hashtable Key-Value: {5=Five 3=Three 2=Two 1=One} Size of Hashtable is : 4 Key '3' exist: true Key '6' exist: false After clearing Hashtable: {}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264138.html