Java中的字典方法


Dictionary是一個抽象類,它表示一個鍵值儲存庫,其工作方式與Map非常相似。給定一個鍵和值,您可以將值儲存在Dictionary物件中。一旦值被儲存,您可以使用它的鍵來檢索它。因此,像地圖一樣,字典可以被認為是鍵值對的列表。

以下是Dictionary定義的方法:

序號方法及描述
1Enumeration elements( )
返回字典中包含的值的列舉。
2Object get(Object key)
返回包含與鍵關聯的值的物件。如果鍵不在字典中,則返回null物件。
3boolean isEmpty( )
如果字典為空,則返回true;如果它包含至少一個鍵,則返回false。
4Enumeration keys( )
返回字典中包含的鍵的列舉。
5Object put(Object key, Object value)
將鍵及其值插入到字典中。如果鍵不在字典中,則返回null;如果鍵已在字典中,則返回與鍵關聯的先前值。
6Object remove(Object key)
移除鍵及其值。返回與鍵關聯的值。如果鍵不在字典中,則返回null。
7int size( )
返回字典中的條目數。

以下是一個實現Dictionary類的put()和get()方法的示例:

示例

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      Dictionary dictionary = new Hashtable();
      dictionary.put("20", "John");
      dictionary.put("40", "Tom");
      dictionary.put("60", "Steve");
      dictionary.put("80", "Kevin");
      dictionary.put("100", "Ryan");
      dictionary.put("120", "Tim");
      dictionary.put("140", "Jacob");
      dictionary.put("160", "David");
      System.out.println("Value at key 20 = " + dictionary.get("20"));
      System.out.println("Value at key 40 = " + dictionary.get("40"));
      System.out.println("Value at key 30 = " + dictionary.get("30"));
      System.out.println("Value at key 90 = " + dictionary.get("90"));
   }
}

輸出

Value at key 20 = John
Value at key 40 = Tom
Value at key 30 = null
Value at key 90 = null

讓我們再看一個示例,其中我們還使用elements()方法顯示Dictionary值:

示例

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      Dictionary dictionary = new Hashtable();
      dictionary.put("20", "John");
      dictionary.put("40", "Tom");
      dictionary.put("60", "Steve");
      dictionary.put("80", "Kevin");
      dictionary.put("100", "Ryan");
      dictionary.put("120", "Tim");
      dictionary.put("140", "Jacob");
      dictionary.put("160", "David");
      System.out.println("Dictionary Values...");
      for (Enumeration i = dictionary.elements(); i.hasMoreElements();) {
         System.out.println(i.nextElement());
      }
      System.out.println("Value at key 20 = " + dictionary.get("20"));
      System.out.println("Value at key 40 = " + dictionary.get("40"));
      System.out.println("Value at key 30 = " + dictionary.get("30"));
      System.out.println("Value at key 90 = " + dictionary.get("90"));
   }
}

輸出

Dictionary Values...
Tom
Jacob
Steve
Ryan
David
John
Kevin
Tim
Value at key 20 = John
Value at key 40 = Tom
Value at key 30 = null
Value at key 90 = null

更新於:2019年9月24日

1K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.