More on Interfaces

This lesson continues discussion of interfaces in Java.

We'll cover the following...

Question # 1

Is the complexity of the following code snippet O(n) always?

    void printName(List<String> names) {
        for(int i=0; i<names.size(); i++) {
            System.out.println(names.get(i));
        }
    }

This is a classic Java interview trick question! The List interface variable names in this snippet could be pointing to an instance of an ArrayList or an instance of a LinkedList. If the list is an arraylist, then the loop runs for O(n) since the get operation is equivalent of indexing into an array. However, the loop runs for O(n2) if the list is a linked list! Therefore, it is always advisable to use the for-each loop if the list type isn't known in advance as the Iterator interface will hide the iteration complexity and will also be the most optimized approach of iterating over the list elements.

Question # 2

...