wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException" Watch "ClassCastException" New topic
Author

ClassCastException

Padma Priya
Ranch Hand

Joined: Feb 01, 2007
Posts: 112
hi Everyone,

I am trying to convert an array to a List


String[] sa = {"one", "two", "three", "four"};
List sList = (ArrayList)Arrays.asList(sa);

but I get a classcastexception......can anybody explain???

WithRegards
Deepthi
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Depthi,


String[] sa = {"one", "two", "three", "four"};
List sList = (ArrayList)Arrays.asList(sa);

but I get a classcastexception......can anybody explain???


Actually Arrays.asList(args); returns List (reference to the List) and
List can't be casted to (recall downcasting in such a case that fails later) ArrayList.

But at the runtime type sList is ArrayList.
Try this:



Got it?



Regards,
cmbhatt


cmbhatt
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
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

Joined: Oct 13, 2005
Posts: 36508
    
  16
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

Joined: Oct 13, 2005
Posts: 36508
    
  16
. . . 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.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

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.


And no need to unzip src.zip, looking at the online API is enough :
http://java.sun.com/j2se/1.5.0/docs/api/


[My Blog]
All roads lead to JavaRanch
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707

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.


Satou, what I wanted to say is as following:




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.


The same, applies to all the base types: In our previous example


Above code compiles fine but fails later. asList(...) returns List so
can't be casted to ArrayList.

ArrayList IS-A List but vice versa may not be true (talking about runtime type)

Is it still a fuss?


Regards,
cmbhatt

*At run time.
[ April 12, 2007: Message edited by: Chandra Bhatt ]
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Satou,

Please correct me in my previous post, if it goes wrong!
A little contradiction!!!

Anybody else may please pay a little attention there!

Thanks,
cmbhatt
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18118
    
  39

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).


This is tangent to the on-going discussion, but I thought that I should mention...

You actually don't get a java.util.ArrayList object back from the Arrays.asList() method. If you did, then the cast should work fine at runtime. What you get back is a private static inner class of the java.util.Arrays class, called ArrayList. It's a different ArrayList class from the java.util.ArrayList class -- hence, the class cast exception.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Thanks a lot Henry,

Your this summary helps me a lot!!!


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


What I got from this code:
java.util.Arrays$ArrayList

The output was interesting and and what you said:
What you get back is a private static inner class of the java.util.Arrays class, called ArrayList. It's a different ArrayList class from the java.util.ArrayList class, so the ClassCastException

These were refreshing lines! Good!



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!

Thanks,
cmbhatt
[ April 15, 2007: Message edited by: Chandra Bhatt ]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18118
    
  39

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.

Henry
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Thanks for reminding java.lang.UnsupportedOperationException thrown by add() and remove() methods of the Arrays.ArrayList class!



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?


Please suggest!




Regards,
cmbhatt
[ April 15, 2007: Message edited by: Chandra Bhatt ]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18118
    
  39

Does Arrays.ArrayList implement List?


yes
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
Private inner class? I never realised that. Thank you, Mr Wong.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Arrays.ArrayList extends AbstractList!


Thanks,
cmbhatt
[ April 15, 2007: Message edited by: Chandra Bhatt ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ClassCastException
 
Similar Threads
Contact[] cts = (Contact[]) list.toArray(); why this casting does not work.
Collection.toArray() method
toArray question
toArray() method
How is priority determined?-Collection Doubt