• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
harish patarla
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>?
 
Daniel Cox
Ranch Hand
Posts: 147
7
  • 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.
 
Charissa Thomas
Greenhorn
Posts: 8
  • 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:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic