0

Iterate through the linkedlist is like this: -

    LinkedList<Integer> ll = new LinkedList<Integer>();
    Iterator<Integer> itr = ll.iterator();
    while (itr.hasNext()) {
        int val = itr.next();
    }

Question is how to unit test(eg: if elements are 1, 2, 3, 4 in sequence is the unit test case, or example a sortLinkedList function, etc.) such collections where only way to loop through them is through Iterator ? Also please refrain from giving solutions that involve Guava.

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132

2 Answers2

0

There are several possibilites. You won't get around creating an object that you can assert like a string or a collection. assert.

To do this you can build a helper function that you can reuse in your tests.

Check this post for asserting collections.

Community
  • 1
  • 1
Jesko R.
  • 827
  • 10
  • 21
0

You can do something like this:

LinkedList<Integer> ll = new LinkedList<Integer>();
Iterator<Integer> itr = ll.iterator();

int i = 0;
int[] seq = {1, 2, 3, 4};

while (itr.hasNext()) {
    int val = itr.next();
    assertEquals(seq[i], val);
    i++;
}

Or even simpler, use an enhanced for loop:

LinkedList<Integer> ll = new LinkedList<Integer>();

int i = 0;
int[] seq = {1, 2, 3, 4};

for (Integer val : ll) {
    assertEquals(seq[i], val);
    i++;
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386