Win a flower (🌹) or copy of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java (📚) 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
master stewards:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
garden masters:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
gardeners:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

Collection

  • 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>();
}
 
Marshal
Posts: 25162
64
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
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: 68008
258
  • 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?
 
pioneer
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.
 
When it is used for evil, then watch out! When it is used for good, then things are much nicer. Like this tiny ad:
Try Free Java/.NET Libraries for Word Excel PowerPoint and PDF
htttp://www.e-iceblue.com/free-apis.html
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!