That is an interesting phenomenon. Chandra Bhatt is quite correct; you declare a List (which is "abstract" as an interface) and obtain a class object (concrete class, java.util.ArrayList).

Anybody seen that happen elsewhere?

Campbell Ritchie

Sheriff

Posts: 51448

87

posted 9 years ago

Go into your JDK folder, find the file called "src.zip," unzip it, find "Arrays.java" in the java -> util folders, and open it with a text editor, use ctrl-F "asList," and there you will find this:

// Misc

/** * Returns a fixed-size list backed by the specified array. (Changes to * the returned list "write through" to the array.) This method acts * as bridge between array-based and collection-based APIs, in * combination with {@link Collection#toArray}. The returned list is * serializable and implements {@link RandomAccess}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); * </pre> * * @param a the array by which the list will be backed * @return a list view of the specified array */ public static <T> List<T> asList(T... a) { return new ArrayList<T>(a); }

Simple, isn't it!

Campbell Ritchie

Sheriff

Posts: 51448

87

posted 9 years ago

. . . And of course, I thought 5 minutes after the previous posting, it is not possible to return a List qua List; it is abstract and one must return a concrete implementation of List. ARrayList<T> is the most popular type.

What makes us able to modify the existing elements of the List returned by asList() of Arrays class but fails when we add new item. I know it returns fixed elements list. (No addition possible) "Reference can point to another object (mutability) but no new reference can be added" If correct!

What makes us able to modify the existing elements of the List returned by asList() of Arrays class but fails when we add new item. I know it returns fixed elements list. (No addition possible) "Reference can point to another object (mutability) but no new reference can be added" If correct!

Basically, it is implemented that way. The inner class has a set() and get() method that uses the array as the backing store. And has add() and remove() methods, that throw "unsupported" exceptions.