reverse a list of generic type Q: Given a list, reverse the order of its elements (don't use
  collections).


Here is my solution:

public static &lt;T&gt; void reverse(List&lt;T&gt; list) {
    if (list.size() &gt; 0) {
        T t;
        t = list.get(0);
        list.remove(0);
        reverse(list);
        list.add(t);
    }
}



I want to know if this is an efficient way of reversing a list
Is this working for every list as input?
No and no. This is a very inefficient way to reverse, for example, a dynamic array based list (it's a different story with a linked list). With a dynamic array based (e.g. ArrayList) The remove(0) operation will require moving every other element in the list (linear in the length), so the whole method is quadratic in the total length of the list. It also requires a linear number of stack frames, which are actually pretty expensive and if you ask for too many the program will crash, which means this method will not work for long lists.

An efficient solution would work in linear time with a constant space requirement.



When thinking about inputs, it's important to also consider null as a possible input. The deficient spec does not indicate what should be done with a null input, which means you have had to make a decision, and that decision should be documented. The 'easy' (and often best) option is to explicitly test for a null input and throw an IllegalArgumentException exception, so that anyone using your method receives a useful error message. You could argue that your code should do nothing with a null, but that's a bit iffy, because the spec doesn't qualify the behaviour, and that would 'silently' fail if someone passed it a null incorrectly: throwing an exception forces any unexpected usage to be address directly, which may or may not prompt a decision change, which makes it a good 'default' choice.



There is no need here to pre-declare t: just declare and assign it in one go:

T t = list.get(0);


This makes it easier to find out what it means. You could also make it final in this case, so that it is entirely clear that it is only assigned once, which makes it that little bit easier to reason about the code.



When writing recursive code like this, it can pay select the 'most ideal' base case. In this instance, any list of length no more than 1 is already reversed, so you could change the if condition to list.size() &gt; 1. This doesn't change the complexity, but is something of which to be aware.