This week's book giveaway is in the Functional programming forum.
We're giving away four copies of Functional Design and Architecture and have Alexander Granin on-line!
See this thread for details.
Win a copy of Functional Design and Architecture this week in the Functional programming 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
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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

 
Greenhorn
Posts: 5
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

reply
    Bookmark Topic Watch Topic
  • New Topic