这可能是个愚蠢的问题,但我很难想清楚。
我编写了一个使用 LinkedList 在加载的 MIDI 乐器中移动的方法。我想制作一个下一个和一个上一个按钮,以便每次单击该按钮时都会遍历 LinkedList。
如果我多次硬编码 itr.next();
或 itr.previous();
我可以遍历 LinkedList
public void setInsturment(Synthesizer start,MidiChannel currentChannel[])
{
try
{
start.open();
Soundbank bank = start.getDefaultSoundbank();
start.loadAllInstruments(bank);
LinkedList<Instrument> currentInstrument = new LinkedList<Instrument>();
Instrument instrs[] = start.getLoadedInstruments();
currentInstrument.add(instrs[0]);
currentInstrument.add(instrs[1]);
currentInstrument.add(instrs[2]);
currentInstrument.add(instrs[3]);
currentInstrument.add(instrs[4]);
ListIterator itr = currentInstrument.listIterator();
itr.next();
itr.next();
itr.next();
// nextInstrument();
currentChannel[1].programChange(0,itr.nextIndex());
}
catch(MidiUnavailableException e)
{
System.out.print("error");
}
}
我在制作一个可以遍历列表的按钮时遇到了很多麻烦。有没有一种有效的方法来做到这一点?我尝试过类似的方法但没有成功。
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == nextButton)
{
sound.nextInstrument();
}
public void nextInstrument()
{
itr.next();
}
提前谢谢大家!
最佳答案
嗯,嗯,链表是一个列表,它的项目可以通过索引访问,这不是通过索引访问项目的最佳结构,但我真的不知道你是否可以在那种类型上使用游标集合,但您可以将当前索引存储在实例变量上。
如果你真的想要随机访问,那么你应该考虑使用 ArrayList 而不是链表。
例子:
class NextPrevList {
private int index = 0;
private List currentList; //initialize it with some list
public Object next() {
return list.get(++index);
}
public Object prev() {
//maybe add a check for out of bounds
if (index == 0) return null;
return list.get(--index);
}
}
我个人认为 ArrayList 比 LinkedList 性能更好
关于java - 使用 LinkedList 实现下一个和上一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290817/