String[] sa = {"one", "two", "three", "four"};
List sList = (ArrayList)Arrays.asList(sa);
but I get a classcastexception......can anybody explain???
cmbhatt
Simple, isn't it!
// 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);
}
List can't be casted to (recall downcasting in such a case that fails later) ArrayList.
[My Blog]
All roads lead to JavaRanch
I don't understand all that fuss about it Chandra said it all :
List can't be casted to (recall downcasting in such a case that fails later) ArrayList.
Dog IS-A(n) Animal but vice versa may not be true (talking about runtime type) That is why we do instanceof test before downcasting of course.
cmbhatt
cmbhatt
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).
Excerpts from my previous post (reply)!
String[] sa = {"one", "two", "three", "four"};
List sList = Arrays.asList(sa);
System.out.println(sList.getClass()); //Added line to your code
I would like to ask one more question by the way:
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!
Your comment please!
cmbhatt
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!
Runtime type of what Arrays.asList() returns is Arrays$ArrayList that is different from the ArrayList that IS-A List.
But Arrays.asList() returns List (What is that List)
Does Arrays.ArrayList implement List?
cmbhatt
Does Arrays.ArrayList implement List?
cmbhatt