Skip to content

Iterator.head()/tail() does not follow Traversable contract #2936

@digiovinazzo

Description

@digiovinazzo

Traversable interface is extended by several other interfaces of collections, one of those is Iterator.
But it behaves differently than the others when using head() and tail() methods, see here below the test that fails for Iterator, but not for all other sequential collections.

class ScratchTest {
    public static void main(String[] args) {
        testTraversable(LinkedHashSet.of(0, 1, 2, 3));
        testTraversable(List.of(0, 1, 2, 3));
        testTraversable(Queue.of(0, 1, 2, 3));
        testTraversable(Array.of(0, 1, 2, 3));
        testTraversable(Vector.of(0, 1, 2, 3));
        testTraversable(Iterator.of(0, 1, 2, 3)); // fails!
    }

    private static void testTraversable(Traversable<Integer> traversable) {
        assertEquals(Integer.valueOf(0), traversable.head());
        traversable = traversable.tail();
        assertEquals(Integer.valueOf(1), traversable.head());
        traversable = traversable.tail();
        assertEquals(Integer.valueOf(2), traversable.head());
        traversable = traversable.tail();
        assertEquals(Integer.valueOf(3), traversable.head());
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions