簡體   English   中英

如何使用哈希表和存儲桶哈希

[英]How to use hashtable and bucket hashing

因此,最近我一直在嘗試進行哈希處理,並在表中使用鏈表來存儲值。 我理解這個概念,但是在實踐中遇到困難,而且似乎找不到我在網上尋找的東西。

例如:假設我想使用一個哈希表來存儲諸如計算機,監視器,鼠標等之類的東西。我想要諸如以下的方法:

boolean addMonitor(String id, String description, double price, int units, String size)

boolean addMouse(String id, String description, double price, int units, int buttons)

我不明白如何使用這些方法將它們存儲在哈希表中。 我顯然很想在以后使用其他方法來訪問和更改每個值。 任何幫助表示贊賞。 謝謝。

即使其名稱表示“表”,HashTable也不像“數據庫表”那樣具有列,並且每個列都存儲值...似乎您想將哈希表用作數據庫表。

哈希表存儲對象! 因此,您的方法應該看起來像這樣更好:

public class Example {

    public static void main(String[] args) {
        ItemStore store;
        Monitor monitor;
        Mouse mouse;

        store = new ItemStore();
        monitor = new Monitor();
        monitor.id = 2;
        monitor.price = 6;

        mouse = new Mouse();
        mouse.id = 7;
        mouse.buttons = 3;

        store.addItem(monitor);
        store.addItem(mouse);

        System.out.println(store.getItem(2).price);   // = 6
        System.out.println(((Monitor) store.getItem(2)).dpi);
        System.out.println(((Mouse) store.getItem(7)).buttons); //Downcasting ... = 3
    }
    public static class Item {
       String id;
       String description;
       int price;
       // common attributes here!
    }

    public static class Monitor extends Item {
        private int dpi;
       // monitor particular atributes here!!
    }

    public static class Mouse extends Item {
        private int buttons;
        // mouse particular attributes here!!!
    }


    public static class ItemStore {
       private Hashtable<String, Item> table = new HashTable<>();

       public boolean addItem(Item item) {
           this.table.put(item.getId(), item);
       }

       public Item getItem(String id) {
           return this.table.get(id);
       }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM