Because you mention the cons
function, I will assume that you're approaching this problem with the conceptual model of linked lists composed of cons
cells. Specifically, I assume that you're thinking of each list having a car
(the first element) and a cdr
(the sublist containing all following elements).
Java supports linked lists as java.util.LinkedList
. These are good for linear traversal and can have elements inserted very efficiently. These are most similar to the linked lists I mentioned above.
Java also offers java.util.ArrayList
. Lists of this kind are good for random access, but can be slow when inserting elements. In fact, they are slowest when inserting an element at the beginning of the list. Because ArrayList
s are implemented as arrays behind the scenes, every element must be copied one position forward in the list to make room for the new first element. Now, if you also happen to need a bigger array, the ArrayList
will allocate a new array, copy all the elements over, and so on.
(Google's ImmutableList
is cited as "random-access", so it is likely more similar to the latter.)
If you plan to use your cons
method often, I recommend using it with linked lists. A cons
operation is essentially adding an element at the beginning of a list. This makes little sense with linear structures such as arrays. I recommend against using array lists for this reason: that they're conceptually wrong for the job.
For the very picky: because a new list is returned each time cons
is called, copying must occur whether the list is a LinkedList
or an ArrayList
. However, the entire principal of a cons
operation is that it is operating on a linked list.
public <E> LinkedList<E> cons(E car, List<E> cdr) {
LinkedList<E> destination = new LinkedList<E>(cdr);
destination.addFirst(car);
return destination;
}
Note that the above code was written after reading the above answers, so I apologize for any accidental plagiarism. Let me know if you see it and I'll properly acknowledge.
Assuming you're happy with returning a LinkedList
, you can use ImmutableList
as the cdr
in this example.