繁体   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