Search code examples
javalistlistiterator

Visit every couple of element of a generic List in Java only once


I have a List in Java, and I would like to exploit a visit for every couple of element only once. For example if I had an Array I would have done something like:

O[] x = ...;
for(int i = 0; i<x.length; i++){
     for(int j=i+1; j<x.length;j++){
          someOperation(x[i],x[j]);
     }
}

The problem is that I have a List (and we suppose to don't know if the List is an ArrayList or a LinkedList). In order to have the same complexity as the case listed before, I would write in pseudo-code, something like:

 ListIterator<O> it1 = list.listIterator();
 while(it1.hasNext()){
      O x = it1.next();
      it2 = it1.clone();   //it2 have the same "status" of it1, but it is a different object in memory
      while(it2.hasNext()){
           y= it.next();
           someOperation(x,y);
      }
 }

As far as I know we don't have anything like it1.clone(). The only way to do a similar stuff it is more or less:

 int i = it1.nextIndex();
 it2 = list.listIterator(i);

but, as far as I know,

 list.listIterator(i);

could have a complexity of O(n) - in the case of a LinkedList, and this is absolutely avoidable in other languages. On the other side, implementing the same algorithm using a random access (like list.get(i)), would be even worst. What is the correct way to write the code assuming that the list is a LinkedList?


Solution

  • Can't you just swap i and j?

    List<E> x = ...;
    int j = 0;
    for (E ej : x) {
        int iMax = j++;
        int i = 0;
        for (E ei : x) {
            if (i++ >= iMax)
                break;
            someOperation(ei, ej);
        }
    }