• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collection  RSS feed

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if this is true:

List<Integer> l = new ArrayList<Integer>();

why isn't this true:

public List<Integer> method()
{
return new ArrayList<Integer>();
}
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What do you mean by "true" in those examples? And why do you say that one is "true" and the other one isn't?
 
Madhurendra Narayan Tiwary
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i mean to say the first one compiles fine that is we can assign a ArrayList in a List type variable but when we try to return an ArrayList where return type is List it causes error, why is that?
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your code compiled when I tried it. What sort of error message do you get?
 
Ranch Hand
Posts: 411
5
IntelliJ IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You code is legal for the reason that an ArrayList implements List, therefore anywhere a list is required you can pass an instance of ArrayList which is called upcasting or the more technical concept around this context programming to an interface.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!