Arrays.asList(T…) , A List which is not really a List

In Java 6 or 7, the relative heaviness of the add operation in a list often encourages me to wonder if Arrays.asList() is convenient for my need.

It’s sure that :

private void shortAdd() {

    Record r1 = new Record("java", 1);
    Record r2 = new Record("erlang", 2);
    Record r3 = new Record("php", 3);
    List<Record> records = Arrays.asList(r1, r2, r3);
}

is simpler than :

private void verboseAdd() {
    Record r1 = new Record("java", 1);
    Record r2 = new Record("erlang", 2);
    Record r3 = new Record("php", 3);

    List<Record> records = new ArrayList<Record>();
    records.add(r1);
    records.add(r2);
    records.add(r3);
}

But the prolbem is that the List<T> returned by Arrays.asList(T... t) has some limitations.
The main is clearly indicated in the javadoc :
"Returns a fixed-size list backed by the specified array. 
(Changes to the returned list "write through" to the array.)"

So, our returned list which implements the java.util.List 
interface is not a real List since main limitations 
that an array has, this List implementation has.
Dynamic changes on this implementations are not supported.
All the add and remove operations trigger some 
UnsupportedOperationException.
In the hoods, Its implementation (from JDK5 at least) lies mainly
 on java.util.AbstractList, a shared and limited skeleton 
implementation of java.util.List.

So, yes, I use this factory method but before, I take always 
30 seconds to verify that its limitations would not bother me.

IMHO, I found that Arrays.asList(T...) is not a very relevant name.
A List implementation with as many as 
UnsupportedOperationException cannot be considered as a classic List.
I have already done the 
error several times to use it by forbidding its limitations. 
Arrays.asNotDynamicList() or Arrays.asLimitedList() would be better. 
Ce contenu a été publié dans Uncategorized. Vous pouvez le mettre en favoris avec ce permalien.

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *