如何返回ArrayList中的下一个和上一个对象

时间:2018-12-08 17:41:15

标签: java arraylist

我正在创建将用于按钮的方法,该方法将返回数组中的下一个Photo对象,当其结束时将重新遍历列表。另一个将获得前一个照片对象,并在到达起点时从终点开始

我的问题是,循环总是返回true,如果我使用listIterator.next,则会收到错误消息,如果有帮助的话,我的课程也将实现收集

public Photo next() {
    ListIterator<Photo> listIterator = PhotoAlbum.photo.listIterator();
    if (this.size() == 0) {
        return null;
    }
    if (listIterator.hasNext()) {           
        Photo output = listIterator.next();

        return output;
    } 
    return PhotoAlbum.photo.get(0);

}

public Photo previous() {
    ListIterator<Photo> listIterator = PhotoAlbum.photo.listIterator();
    if (this.size() == 0) {
        return null;
    }
    if (listIterator.hasPrevious()) {
        return listIterator.previous();
    } 
    return PhotoAlbum.photo.get(this.size()-1);



}    

2 个答案:

答案 0 :(得分:2)

您应该将照片的当前索引存储在变量中。

private int currentPhotoIndex = 0;

然后您的函数将根据操作对其进行递增/递减

private int currentPhotoIndex = 0;

public Photo next() {
    if (this.size() == 0) {
        return null;
    }

    if (this.currentPhotoIndex < this.size()) {
        this.currentPhotoIndex++;
    } else {
        this.currentPhotoIndex = 0;
    }

    //I think here it should be: return this.get(currentPhotoIndex), but I sticked to your code
    return PhotoAlbum.photo.get(currentPhotoIndex);

}

public Photo previous() {
    if (this.size() == 0) {
        return null;
    }
    if (this.currentPhotoIndex > 0) {
        this.currentPhotoIndex--;
    } else {
        this.currentPhotoIndex = this.size() - 1;
    }

    //I think here it should be: return this.get(currentPhotoIndex), but I sticked to your code
    return PhotoAlbum.photo.get(currentPhotoIndex);
} 

答案 1 :(得分:0)

您可以使用ListIterator轻松完成此操作,下面是一个示例。

public class Main {

    public static void main(String[] args) {

        List<String> names = new ArrayList<>();
        names.add("Thomas");
        names.add("Andrew");
        names.add("Ivan");

        ListIterator li = names.listIterator();

        while(li.hasNext()) {
            System.out.println(li.next());
        }

        while(li.hasPrevious()) {
            System.out.println(li.previous());
        }
    }
}

当然,这只是一个简单的示例,但是您可以根据需要进行调整。