创建具有预定长度的数组ArrayList

时间:2015-11-01 22:10:22

标签: java arrays list arraylist

基本上,我正在寻找创建一个Notes数组的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中可能存在或可能不存在的所有数组(因为我们不知道ArrayList大小何时/如何/经常更改)到a大小为120,如果不可能,则在这种情况下是否有可能使用更好的数据结构。谢谢!

2 个答案:

答案 0 :(得分:2)

长度为120的数组没有数据类型,因此您不能拥有List<Note[120]>List<Note[]>,其中每个数组都保证长度为120。你能做的就是自己上课:

public final class TenOctaves {

    private static final int NUMBER_OF_NOTES = 120;

    private final Note[] notes = new Note[NUMBER_OF_NOTES];

    public void setNote(int position, Note note) {
         if (position < 0 || position >= NUMBER_OF_NOTES)
             throw new IllegalArgumentException();
         notes[position] = note;
    }

    public Note getNote(int position) {
        if (position < 0 || position >= NUMBER_OF_NOTES)
             throw new IllegalArgumentException();
        return notes[position];
    }
}

然后你可以改为List<TenOctaves>

答案 1 :(得分:1)

如果我正确理解您,您可以使用子类化ArrayList并实现您自己的特殊add逻辑。

public class NoteList extends ArrayList<Note[]> {

    private final int SCORE_LENGTH = 120;
    private final int MAX_ELEMENTS = 8;

    @Override
    public boolean add(Note[] score) {
        return this.size() <= MAX_ELEMENTS && score.length == SCORE_LENGTH && super.add(score);
    }
}

如果符合以下条件,您将无法在列表中添加元素:

  • 列表的大小大于8
  • 您要添加的阵列的长度不是120