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);
}
解决方案
您应该将照片的当前索引存储在变量中。
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);
}
推荐阅读
- javascript - 在 JavaScript 项目中使用 DTO 处理 json 数据
- c# - 尝试使用托管访问连接 Azure DataLake 但出现未经授权的错误
- firebase - 需要在flutter中使用nullsafey将当前位置添加到firestore
- python - 如何使用 Python 在已经存在的时间范围内添加秒数
- python - python中方法的参数如何工作?
- json-schema-validator - AJV JSON Schema 验证优先于一个查询字符串
- javascript - fetch 如何在请求中发送 auth token
- java - @NotNull 注释不起作用 - 传递 null 时不抛出异常
- haskell - Attoparsec:匹配任何具有公共前缀的字符串
- pandas - 如何将逗号分隔的行转换为列并保存到文件