• Post Reply Bookmark Topic Watch Topic
  • New Topic

which statement more flexible ?  RSS feed

 
Nakata kokuyo
Ranch Hand
Posts: 472
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, wondering is there any advantages over each other?

if i code using :

List list = new ArrayList();

would it be better than

ArraList list = new ArrayList();

which one is better ? thank you
 
Scott Selikoff
author
Bartender
Posts: 4093
21
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In practice, the first is much better.

Since List is a common type, it allows you (should you ever want to change from ArrayList to LinkList) to do this without having to modify tons of code. The more common example, I think, is Set x = new HashSet(). Its common that you might want to change to some ordered set in certain circumstances such as a TreeSet and again, this will give you greater freedom.

Also, if you write methods that take as input an ArrayList, someone with another type of list would not be allowed to use it, so your code has much more freedom.

Alternatively, the only time you do want to specify the more precise type is if you are using a particular feature of the subset. For example, if I am using an iterator on a TreeSet, I may need to know that the elements are in order so I won't allow just any to be passed in, thereby forcing the calling to pre-organize their set. If this is the uncommon case though, you can always call instanceof to be sure.
[ November 22, 2005: Message edited by: Scott Selikoff ]
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is an interview with design patterns guru Eric Gamma about why you should program to an interface, not an implementation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!