2016-05-04 37 views
0

所以最近我一直在嘗試使用哈希和在表中使用linkedlists來存儲值。我理解這個概念,但是我很難將其付諸實踐,並且似乎無法找到我在線尋找的內容。如何使用散列表和桶散列

例如: 比方說,我想用一個哈希表來存儲的東西像一臺計算機,如顯示器,鼠標,等我想的方法,如:

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

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

我不瞭解如何使用這些方法將它們存儲在散列表中。我顯然希望使用其他方法訪問並更改每個值。任何幫助表示讚賞。謝謝。

回答

0

即使它的名字是「table」,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); 
     } 
    } 
} 
+0

有了一個哈希表,我還以爲你可以存儲一個對象,它會指向一個鏈表,這樣你可以有發言權一個對象,但該對象也有一堆其他數據? – MarkMAM

+0

是的,你可以......我的例子(我相信)可以說明這一點,但是採用了更簡化(封裝)的方式! ... –

+0

好的,我可以使用我在頂部提供的方法,但是在存儲時只使用ID進行比較? – MarkMAM