繁体   English   中英

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

[英]how to return Next and previous object in ArrayList

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

我的问题是循环始终返回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);



}    

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

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

您可以使用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());
        }
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM