【问题标题】:How would I correctly use arrays in this case?在这种情况下,我将如何正确使用数组?
【发布时间】:2016-04-11 06:30:03
【问题描述】:

我创建了两个类,WaitlistPartyWaitlist 类将与LocalTimes 列表一起使用,并为每个LocalTime 分配多个Partys。我不清楚我是否应该创建一个LocalTimes 数组和一个Party[]s 数组,或者我是否应该以某种方式使用ArrayLists,或者在这种情况下HashMap 是否是一个不错的选择。

Waitlist.java

public class Waitlist {

    private static final int N = 74;
    private LocalTime[] times;
    private ArrayList<Party>[] slots;
    private HashMap<LocalTime, ArrayList<Party>[]> list;

    public Waitlist() {
    // initialize variables

    //init `times`
    times = new LocalTime[N];
    slots = new ArrayList[N];
    int h = 9; // open
    int m = 0;
    for (int i = 0; i < N; i++) {
        slots[i] = new ArrayList<>();
        times[i] = LocalTime.of(h, m);
        if (m == 48) {
        h++;
        m = 0;
        } else {
        m += 12;
        }
    }
    }
}

【问题讨论】:

  • 数组和列表本质上是一回事。两者都与Map 非常不同,后者可能代表一种关系。花一些时间研究和理解基本数据结构和示例用例 - 如果没有这些理解基础,我们将不清楚如何更好地为您解释差异。

标签: java arrays arraylist hashmap


【解决方案1】:

在这里,哈希映射似乎是您最好的选择。因为您有一个时间关联方,您可以将键设置为时间,值将是列表。当按时间访问(我假设您将这样做)并且仅迭代列表时,这允许非常有效地检索当事方列表。这将比在两个单独的列表上执行搜索以获取关联更快。此外,HashMaps 还为键提供迭代器,因此如果您需要时间列表,您可以使用它。

具体来说,您的 HashMap 的数据类型应如下所示。

HashMap<LocalTime, ArrayList<Party>> parties;

至此,聚会就这么简单

parties.get(time).get(index);

目前我正在编写一种伪代码,因为我不在我的机器附近,但总体思路就在那里。

【讨论】:

  • 那么我可以在逻辑上使用LocalTimes 作为索引吗?即parties.get(LocalTime.of(9, 24)) 将返回安排在 9:24 的派对的 ArrayList?
  • 是的。这正是它的工作方式。如果数据集足够小,您应该会看到检索该数组的复杂度为 O(1)。
猜你喜欢
  • 2020-08-06
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-02
  • 2013-11-21
相关资源
最近更新 更多