簡體   English   中英

訪問類及其元素中的Hashtable,Java

[英]Accessing Hashtable in Class and its elements, Java

我有一個“項目”類,其中包含以下內容......

public class Item{

    private String barcode;

    private String productName;

    private int quantity;

}

我還有一個名為“Store”的類,它包含我的HashTable,就像這樣......

public class Store implements Serializable{

Hashtable<String, Item> store = new Hashtable<String, Item>();

}

String與條形碼相同,是HashTable中Item對象的“鍵”。

現在,在我的主要內容中,我嘗試創建這些類對象的實例,並使用put()方法將項目存儲在Hashtable中,但我似乎無法訪問它。 我想將項目添加到Hashtable中,如果它發現該項目已經存在,則會增加項目數量值。

我對HashTables沒有經驗,有人可以幫忙嗎?

編輯:

代碼在我的主...

Store store = new Store();

    Item item1 = new Item();
    item1.setProductName("Paper Towel Roll");
    item1.setBarCode("111222333444");
    item1.setQuantity(1);

    store.put("111222333444", item1);

試試這樣:

public class Store implements Serializable{
 public Hashtable<String, Item> itemsTable = new Hashtable<String, Item>();
}

在主要:

Store store = new Store();

Item item1 = new Item();
item1.setProductName("Paper Towel Roll");
item1.setBarCode("111222333444");
item1.setQuantity(1);

store.itemsTable.put("111222333444", item1);

添加公共,以便您可以從包中訪問它。 它在“package-private”中,因為沒有指定修飾符。

public class Store implements Serializable{

    private Hashtable<String, Item> items = new Hashtable<String, Item>();

    // Getter and setter for items hashtable

}

主要代碼:

Store store = new Store();

Item item1 = new Item();
item1.setProductName("Paper Towel Roll");
item1.setBarCode("111222333444");
item1.setQuantity(1);

// NOTE: getItems() is the getter for the store object. 
// Don't expose it as public. Bad encapsulation

store.getItems().put(item1.getBarCode(), item1); 

注意:最好避免使用Hashtable和使用HashMap

暫無
暫無

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

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