首页 > 解决方案 > 如何在 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);



}    

标签: javaarraylist

解决方案


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

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);
} 

推荐阅读