Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Collection question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collection question" Watch "Collection question" New topic
Author

Collection question

henri henri
Ranch Hand

Joined: Oct 03, 2005
Posts: 115
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
Sheriff

Joined: Sep 28, 2004
Posts: 18764
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Stuart Ash
Ranch Hand

Joined: Oct 07, 2005
Posts: 637
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.


ASCII silly question, Get a silly ANSI.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
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.


There is no emoticon for what I am feeling!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection question