Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Question on casting

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Everyone

Why doesnt the cast on line 1 work?asList returns List.Why cant we explicitly downcast it to ArrayList?Im getting a ClassCastException.

public static void main(String[] args) {
// TODO code application logic here
String [] str={"1","2","3","4"};
ArrayList l=(ArrayList)(Arrays.asList(str));//line 1
for(String s:str)
System.out.println(s);
System.out.println(l);
l.add(2,"5");
for(String s:str)
System.out.println(s);
System.out.println(l);
}

Thank You.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy, ranchers,

praneeth kumar posted

Why doesnt the cast on line 1 work? asList returns List



No, doesn't.

The Arrays-method return an inner class of Arrays. So wrong type.

e.g.
prints
[-9, -5, 5]
class java.util.Arrays$ArrayList


Yours,
Bu.
 
Tomorrow is the first day of the new metric calendar. Comfort me tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic