Java Dictionary get() 方法



描述

Java Dictionary get(Object key) 方法返回字典中給定鍵對應的值。

宣告

以下是 java.util.Dictionary.get() 方法的宣告

public abstract V get(Object key)

引數

key − 此字典中的鍵。如果鍵未對映到任何值,則可以為 null。

返回值

此方法返回此字典中鍵對映到的值。

異常

從整數、整數對字典中獲取值的示例

以下示例演示了 Java Dictionary get(int) 方法的使用。我們使用 Integer、Integer 對的 Hashtable 物件建立字典例項。然後我們向其中添加了一些元素。使用 get(int) 方法透過傳遞鍵檢索其中一個元素,然後列印。

package com.tutorialspoint;

import java.util.Dictionary;
import java.util.Hashtable;

public class DictionaryDemo {
   public static void main(String[] args) {

      // create a new hashtable
      Dictionary<Integer, Integer> dictionary = new Hashtable<>();

      // add 2 elements
      dictionary.put(1, 1);
      dictionary.put(2, 2);

      System.out.println(dictionary.get(1));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

1

從整數、字串對字典中獲取值的示例

以下示例演示了 Java Dictionary get(int) 方法的使用。我們使用 Integer、String 對的 Hashtable 物件建立字典例項。然後我們向其中添加了一些元素。使用 get(int) 方法透過傳遞鍵檢索其中一個元素,然後列印。

package com.tutorialspoint;

import java.util.Dictionary;
import java.util.Hashtable;

public class DictionaryDemo {
   public static void main(String[] args) {

      // create a new hashtable
      Dictionary<Integer, String> dictionary = new Hashtable<>();

      // add 2 elements
      dictionary.put(1, "One");
      dictionary.put(2, "Two");
      System.out.println(dictionary.get(1));
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

One

從整數、物件對字典中獲取值的示例

以下示例演示了 Java Dictionary get(int) 方法的使用。我們使用 Integer、Student 對的 Hashtable 物件建立字典例項。然後我們向其中添加了一些元素。使用 get(int) 方法透過傳遞鍵檢索其中一個元素,然後列印。

package com.tutorialspoint;

import java.util.Dictionary;
import java.util.Hashtable;

public class DictionaryDemo {
   public static void main(String[] args) {

      // create a new hashtable
      Dictionary<Integer, Student> dictionary = new Hashtable<>();

      // add 2 elements
      dictionary.put(1, new Student(1, "Julie"));
      dictionary.put(2, new Student(2, "Robert"));

      System.out.println(dictionary.get(1));
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

[ 1, Julie ]
java_util_dictionary.htm
廣告