Reputation: 33
I'm creating methods that will be used for buttons one that will return the next Photo object in my array and when it gets to the end will start over moving through the list. The other that will get the previous Photo Object and will start at the end when it reaches the beginning
My issue is that the loop always returns true and if I use listIterator.next
I get an error, my class also implements collection if that helps any
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);
}
Upvotes: 0
Views: 728
Reputation: 743
You can do it simple using ListIterator, here is an example of that.
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());
}
}
}
Of course that is only a simple example, but you can adapt it to your needs.
Upvotes: 0
Reputation: 86
You should store the current index of the photo inside a variable.
private int currentPhotoIndex = 0;
Then your functions will increment/decrement it depending on the operation
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);
}
Upvotes: 2