使用 LinkedList 实现下一个和上一个按钮

2024-06-20

这可能是一个愚蠢的问题,但我很难思考清楚。

我编写了一个使用 LinkedList 来移动加载的 MIDI 乐器的方法。我想制作一个下一个和一个上一个按钮,以便每次单击该按钮时都会遍历 LinkedList。

如果我硬编码itr.next(); or 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而不是链表。

Example:

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 会更具性能

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 LinkedList 实现下一个和上一个按钮 的相关文章

随机推荐