{Array|Linked}List: Proposal of two new C'tors and methods
Hello World!
I would like to hear your opinion about the addition of two new constructors
and two new methods for the concrete implementations of the j.u.List interface
(ArrayList and LinkedList). I show them for the AbstractList class:
First the specifications of the C'tors:
/**
* Creates a new List from the elements of an iterable object.
* The sequence order in the resulting list equals
* the order defined by the argument's iterator.
*/
public AbstractList(Iterable<? extends T> iterable);
/**
* Creates a new List from the elements represented by an iterator.
* The sequence order in the resulting list equals
* the order defined by the argument iterator.
*/
public AbstractList(Iterator<? extends T> iterator);
And here are the methods (I leaf out the obvious comments):
public void addAll(Iterable<? extends T> iterable);
public void addAll(Iterator<? extends T> iterator);
Reasoning:
In Java 1.5 (and in the upcoming 1.6, too), we only have a C'tor for creating a list
from a j.u.Collection. Until 1.4 this was ok, but with the introduction of the
Iterable interface, together with the for-each loop, the definition of iterators
for user defined classes becomes a common task. So this should also be recognized in
the definition of the standard APIs. Currently I have to define utility functions
for this purpose in all my projects. While this is very easy to do (see below),
I feel this is not the right thing to doo -- it should be there out of the box.
The first C'tor and addAll method, which gets an Iterable object as its argument,
is a real generalization of the existing Collection's C'tor and addAll method,
because Collection is a subinterface of Iterable. So this won't break any code,
even if the old C'tor would be replaced by the new. But for efficiency reasons
(no runtime type check), I would keep the Collection C'tor -- this is
luckily possible in Java, because the compiler always uses the most specific
type definition when selecting an overloaded method (here Collection is
more specific than Iterable).
Notice that one could think about pulling up my proposed methods to
all CollectionS. But one has to consider a few things:
* In SetS, only one of the argument's elements will be inserted in the result.
* For non SortedSets, the order of the resulting objects will be unknown.
I think, this would not be a problem.
Here is a straightforward implementation of the C'tors and addAll methods:
public AbstractList(Iterable<? extends T> iterable) {
this(iterable.iterator());
}
public AbstractList(Iterator<? extends T> iterator) {
super();
this.addAll(iterator);
}
private void addAll(Iterable<? extends T> iterable) {
this.addAll(iterable.iterator());
}
private void addAll(Iterator<? extends T> iterator) {
while (iterator.hasNext()) {
this.add(iterator.next());
}
}
Greetings,
Michael

