【发布时间】:2015-11-01 22:10:21
【问题描述】:
本质上,我正在寻找创建笔记数组的 ArrayList:
/**
* Represents the entire musical score, with each index of the ArrayList representing each beat.
* Each array of notes represent the notes that can play on a single beat (up to 120 notes, 12
* notes over 10 octaves.
*/
private List<Note[]> score;
...
score = new ArrayList<>(8); // Initialize ArrayList with capacity of 8
我在这里遇到的第一个(次要)问题首先是 ArrayList 最终可能是任意大小并且可能必须增长很多倍(每次需要额外容量时都会增加一倍),第二个(更重要)问题是我无法将 ArrayList 中包含的数组的长度设置为 120,如下所示:
private List<Note[120]> score;
这让我想到了如何将 ArrayList 中可能存在或不存在的所有数组初始化为大小120,如果不可能,在这种情况下是否有可能使用更好的数据结构。谢谢!
【问题讨论】:
-
new ArrayList<>(8)将初始容量设置为 8,not 将大小设置为 8。 -
@Makoto - 注意,在我的评论中没有明确区别
-
"如果那是不可能的 (...)" - 这可能是可能的,尽管我也不确定。 --- “在这种情况下是否有可能使用更好的数据类型” - 基于块的方法可能更适合这种情况;如果可能,您应该以更小的块处理,而不是分配所有这些空间。
-
不可能只初始化意图。为了能够将列表元素初始化为任何长度,您需要在某处创建它们的代码。在这里您也可以将长度固定为 120。您似乎想要的是列表元素的默认值。
标签: java arrays list arraylist