Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collection question

 
henri henri
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just learned that it is better programming practice if I change TreeMap at the beginning of the second line of code to Map.

Map<String, FilmBean>filmBeans = new TreeMap<String, FilmBean>();

after I do this, I get a compiler error for the return statement at the end of the method.


 
Henry Wong
author
Marshal
Pie
Posts: 20835
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by henri henri:
I just learned that it is better programming practice if I change TreeMap at the beginning of the second line of code to Map.

Map<String, FilmBean>filmBeans = new TreeMap<String, FilmBean>();

after I do this, I get a compiler error for the return statement at the end of the method.


Well, you can't make the change and everything magically still works. You have to change your method to return a Map instead of a TreeMap. And you have to change all the places in your program to use a Map instead of a TreeMap.

Henry
 
Stuart Ash
Ranch Hand
Posts: 637
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's all about object typing.

Please read about this in a good Java textbook, I recommend Bruce Eckel's thinking in Java.

Keywords: Object type, class type, object references, handle, casting.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stuart Ash:
... I recommend Bruce Eckel's thinking in Java...

I second that recommendation. And here's a link to an online version...

http://www.faqs.org/docs/think_java/TIJ3.htm
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To sum up some previous responses, yes it's good programming practice to
"program to the interface" when possible. In your example, it's more important
for your getFilmBeansByLetter method to have return type Map (or Map<String FilmBean>
in Java 1.5) that for its local value filmBeans to have type Map<String FilmBean>
versus TreeMap<String FilmBean>, although the two can go hand-in-hand.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic