簡體   English   中英

哪種Java集合最適合這種情況

[英]Which Java Collection is best for this scenario

在我的應用程序中,我有帶有唯一鍵的小表(文件)(其中大多數都有兩個或多個字段-組成鍵)。 我想為每個小表創建一個類,並將數據加載到Java集合中。 該對象將讀取文件並將數據加載到java集合中。 然后,我想通過鍵值從此集合中獲取數據,以便可以訪問所有字段。 我的問題是我應該使用哪個集合,或者說哪個集合支持多個鍵? 一個鏈接到一個examole將是很好的。 提前致謝!

假設我已經正確閱讀了您的問題(“多個鍵”存在歧義),您想要的是為鍵本身定義一個類,該類包含多個字段並以這樣的方式實現equals()hashCode() :對象可以用作HashMap鍵。

這是一個非常簡單的框架實現(未經測試,省略了一些錯誤處理):

public class MyKey
{
    private String  part1 = null;
    private Integer part2 = null;
    public MyKey(String part1, int part2)
    {
        this.part1 = part1;
        this.part2 = part2;
    }

    @Override
    public boolean equals(Object o)
    {
        if (o == null || !(o instanceof MyKey)) return false;
        return this.part1.equals(((MyKey)o).part1) && this.part2.equals(((MyKey)o).part2);
    }

    @Override 
    public int hashCode()
    {
        return this.part1.hashCode() + this.part2.hashCode();
    }
}

不能完全確定多個鍵的含義。 您可以存儲在集合中並通過鍵/值對獲取的每個“表”的類對我來說是HashMap。

哈希表可能最好地存儲每個表的內容。 哈希表基本上允許您添加任意數量的對象,並且每個對象都有一個唯一的鍵。

我的建議是對每個表文件執行以下操作。 在我的示例中,我假設您將表文件的每一行讀入一個名為Entry ...的對象中。

// Create a new Hashtable, where the contents will be a String (the unique key) and an "Entry" object for the table row of data
Hashtable<String,Entry> entriesTable = new Hashtable<String,Entry>();

for (each line in your table file){
  // Generate the unique value for this row. If there are multiple columns that make up the key,
  // just join them together into a single String
  String key = uniqueColumn1 + uniqueColumn2 + ...;

  // Create an object for your row, if you dont have one already.
  Entry row = new Entry(line);

  // Add the entry to the Hashtable
  entriesTable.put(key,row);
  }

當您想從表中獲取一行時,您可以通過其唯一值來請求它...

Entry entry = entriesTable.get(uniqueColumn1 + uniqueColumn2 + ...);

您可以根據需要添加任意多個對象,前提是每個對象都有一個唯一的鍵。 Hashtable支持添加和刪除值等,因此非常易於使用。

如果需要,還可以將Hashtable轉換為數組,如果需要獲取Hashtable的完整內容,則可以獲取用於遍歷每個條目的Enumerator。

暫無
暫無

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

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