| Author |
ClassCastException ArrayList->List
|
gianni ipez
Ranch Hand
Joined: Jan 02, 2007
Posts: 65
|
|
Hello, a simple question for you. <code> import java.util.*; public class TestArrayList { public static void main(String[] args) { String[] as = {"one","two","three","four"}; ArrayList <String> al; al = (ArrayList)Arrays.asList(as); al.set(2,"another number"); Iterator<String> i = al.iterator(); while (i.hasNext()) { System.out.println(i.next()); } for(String temp : as){ System.out.println(temp); } } } </code> This class raises a ClassCastException at line al = (ArrayList)Arrays.asList(as); I thought that I could cast because "ArrayList instanceof List" is true(List is the type returned by Arrays.asList(array)) Please, where am I wrong? Thanks, Gianni
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
|
The Arrays.asList method simply returns a List, not necessarily an ArrayList.
|
 |
gianni ipez
Ranch Hand
Joined: Jan 02, 2007
Posts: 65
|
|
This clarify, thanks. But then another question: List is an interface, so it doesn't provide implementations of get and set method, am I right? So how can we invoke get and set methods directly from a List? example: Thank you ! Gianni
|
 |
Krishna Potluri
Greenhorn
Joined: Apr 20, 2007
Posts: 19
|
|
Hi ipez, Because al accepts only strings while casting ___________________________________________________ al = (ArrayList)Arrays.asList(as); ArrayList <String> al; ___________________________________________________ do like this: al = (ArrayList<String> Arrays.asList(as); I am not sure but i hope it works. Thanks, Kris.
|
 |
swarna dasa
Ranch Hand
Joined: Mar 15, 2007
Posts: 108
|
|
It passes back a list inteface, hence you can call methods present in List (polymorphism). Add the following line System.out.println(al.getClass()); what you get is class java.util.Arrays$ArrayList Obviously it is not an java.util.ArrayList but an inner private class ArrayList in java.util.Arrays.
|
 |
gianni ipez
Ranch Hand
Joined: Jan 02, 2007
Posts: 65
|
|
thank you! another little java miracle.
|
 |
 |
|
|
subject: ClassCastException ArrayList->List
|
|
|