• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Arrays.asList() returns an ArrayList object but i can't store it in ArrayList?

 
Greenhorn
Posts: 5
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I was going through chapter 3 about arrays.

I noticed java compiler gives an error when i write below:



But below works fine

I saw that asList is defined as below:


Can anyone please explain why i can't in ArrayList<Integer> but can store in List<Integer>?
 
Ranch Hand
Posts: 231
12
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to know what type a method returns, look at the return type (List<T>), not the return keyword (return new ArrayList<>(a))

This code fails

ArrayList<Integer> integers = Arrays.asList(1,2,3,4);

because Arrays.asList(1,2,3,4) returns a List of Integers and a List of Integers cannot be assigned to an ArrayList of Integers.
 
Greenhorn
Posts: 11
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want to work with the concrete type instead of the interface, you can always cast the returned object before assigning:

 
Why am I so drawn to cherry pie? I can't seem to stop. Save me tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic