I'm writing a code to have 2 lists of integers and iterators for each one. Second one is constructed as reversed first one.
I have a problem with displaying values of the second one using iterator. How to fix that (note that I have used simple for iteration and it works, but want to do it with iterator).
import java.util.*;
public class Ch11Ex12 {
public static void main(String[] args) {
List<Integer> li = new ArrayList<Integer>();
li = Arrays.asList(1, 6, 4, 7);
//List<Integer> li2 = new ArrayList<Integer>();
int z = li.size();
List<Integer> li2 = new ArrayList<Integer>();
/**
for (int index = 0; index < ints.length; index++)
{
li.add(ints[index]);
}
**/
ListIterator<Integer> it = li.listIterator(z);
ListIterator<Integer> it2 = li2.listIterator();
while(it.hasPrevious()){
//System.out.print(it.previous() + " ");
int k = it.previous();
System.out.print(k + " ");
li2.add(k);
}
/**
for (int f = 0; f < li2.size(); f++){
System.out.println(li2.get(f));
}
**/
while(it2.hasNext()){
int p = it2.next();
System.out.print(p + " ");
}
}
}
Define your second Iterator it2 after having filled li2.
ListIterator<Integer> it = li.listIterator(z);
while(it.hasPrevious()){
//System.out.print(it.previous() + " ");
int k = it.previous();
System.out.print(k + " ");
li2.add(k);
}
/**
Now that I have filled li2, I create my ListIterator it2.
**/
ListIterator<Integer> it2 = li2.listIterator();
while(it2.hasNext()){
int p = it2.next();
System.out.print(p + " ");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.