Java Hashtable ตัวอย่าง การใช้งาน Hashtable พร้อม Source Code ให้โหลด

บทความเกี่ยวกับ : Java Hashtable ตัวอย่าง การใช้งาน Hashtable พร้อม Source Code ให้โหลด


Class ใน package java.util อีกตัวคือ Hashtable ตัวนี้จัดเก็บในรูปแบบคู่อันดับเช่นเดียวกันกับ HashMap ต่างกันยังไงนั้นเดี๋ยวเล่าให้ฟังอีกทีนะครับการใช้งานดูเผินๆ ก็เหมือนกันกับ HashMap เลยล่ะครับ คือจัดเป็นในรูปแบบคู่อันดับ อ้างถึงด้วย Key กับ Value นั่นเอง

ตัวอย่าง Java Hashtable
package example.util;
import java.util.*;
public class HashtableExample {
    public void hashtableExample(){
        //Create Hashtable Object
        Hashtable<String,String> hashtable=new Hashtable<String,String>();
        //Store and Remove data from Hashtable
        hashtable.put("key1", "value1");
        hashtable.put("key2", "value2");
        hashtable.put("key3", "value3");
        String key3=hashtable.remove("key3");
       
        System.out.println("-- Example for Get Value from Hashtable --");
        System.out.println("Get Hashtable value: "+hashtable.get("key1"));
        System.out.println("Remove Hashtable value: "+key3);
        System.out.println("Contains Key Hashtable: "+hashtable.containsKey("key1"));
        System.out.println("Contains Key Hashtable: "+hashtable.containsKey("key3"));
        System.out.println("Contains Value Hashtable: "+hashtable.containsValue("value1"));
        System.out.println("Contains Value Hashtable: "+hashtable.containsValue("value3"));
       
        System.out.println("-- Example for Iterate list from Hashtable --");
        Iterator<String> it=hashtable.keySet().iterator();
        while(it.hasNext()){
            String key=it.next();
            String value=hashtable.get(key);
            System.out.println("By Key :Key : "+key+"   Value: "+value);
        }
       
        it=hashtable.values().iterator();
        while(it.hasNext()){
            System.out.println("Value "+it.next());
        }
    }
    public static void main (String args[]){
        HashtableExample hashtable=new HashtableExample();
        hashtable.hashtableExample();
    }
}

ผลการ Run Program

-- Example for Get Value from Hashtable --
Get Hashtable value: value1
Remove Hashtable value: value3
Contains Key Hashtable: true
Contains Key Hashtable: false
Contains Value Hashtable: true
Contains Value Hashtable: false
-- Example for Iterate list from Hashtable --
By Key :Key : key2   Value: value2
By Key :Key : key1   Value: value1
Value value2
Value value1

Note: คำสั่ง Remove ของ Class ตระกูล Collection จะมีการ Return Value Object ที่ลบนั้นออกมานะครับสามารถเก็บไว้ทำประโยชน์ต่อได้

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

Oracle date format จัด format date ให้แสดง พศ และ เดือน ภาษาไทยหรือตามภาษาที่เราเลือก

java -Xms , java -Xmx กำหมด memory ให้ JVM เพื่อป้องกันปัญหา Out of Memory

Java this กับ super การใช้งานคำสั่ง this กับ super ใน ภาษา Java