javainputiteratorcomparelistiterator

Trying to compare the contents two Iterators, how?


EDIT: With your help I managed to fix my problem. I have edited my code to now show how I had to have it set up to get it working.

Currently I am having trouble coding a part which compares the content of two iterators. As part of the requirements for my assignment, I need to use a linkedlist to store the individual characters of the entered String. I have gotten to the point where I have two iterators which would contain the input one way and the reverse way.

        String palindrom = input.getText();
        String [] chara = palindrom.split (""); //this is successfully splitting them, tested.


        int length = palindrom.length( ); // length == 8
        System.out.println (length); //can use this for how many checks to do?
        LinkedList ll = new LinkedList(Arrays.asList(chara));


        Iterator iterator = ll.iterator();
        Iterator desIterator = ll.descendingIterator();

        /*while(iterator.hasNext() ){
            System.out.println(iterator.next() );
        }

        while(desIterator.hasNext() ){
            System.out.println(desIterator.next() );
        }*/
        boolean same = true;
        while(iterator.hasNext()){
            if(!iterator.next().equals(desIterator.next())){
            same = false;
            break;
          }
        }

And using the System.out I can see that they are being stored correctly, but I don't know how to check if the iterators store the same contents. What would be one of the simplest methods to compare the two iterators or convert them into something I can compare? To clarify I want to verify they contain the same elements in the same order.


Solution

  • boolean same = true;
    while(iterator.hasNext()){
      if(!desIterator.hasNext() || !iterator.next().equals(desIterator.next())){
        same = false;
        break;
      }
    }
    
    System.out.println(same);