Reputation: 5770
Essentially, I'm looking to create an ArrayList of Arrays of Notes:
/**
* 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
The first (minor) problem I'm running into here is first that the ArrayList could end up being any size and may have to grow many times (which doubles the size each time it requires additional capacity), and the second (more important) problem is that I'm unable to set the length of the Arrays contained within the ArrayList to 120 as follows:
private List<Note[120]> score;
This brings me to the question of how I can initialize all of the Arrays that may or may not exist in the ArrayList (because we don't know when/if/how often the ArrayList size may change) to a size of 120, and, if that is not possible, whether or not there is potentially a better data structure to be used in this situation. Thanks!
Upvotes: 1
Views: 408
Reputation: 37655
There is no data type for an array of length 120
, so you cannot have a List<Note[120]>
or a List<Note[]>
where every array is guaranteed to have length 120
. What you can do is make your own class:
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];
}
}
Then you could have a List<TenOctaves>
instead.
Upvotes: 2
Reputation: 106460
If I'm understanding you correctly, you could do with subclassing ArrayList
and implementing your own special add
logic.
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);
}
}
You won't be able to add elements to the list if:
Upvotes: 1