Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

List and ArrayList Problem

 
Ganesh Gowtham
Ranch Hand
Posts: 225
IBM DB2 Eclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi frenz

Could u pls explain the below lines
1. List x = ArrayList();

2. ArrayList xy - new ArrayList();

1st line approach is best and prefered ,I want to know the idea that ,Y that 1st line is apt and best
Thnaks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's say you write a thousand lines of code related that that "xy", including lots of small methods that get passed "xy" as a parameter -- i.e., they accept an ArrayList.

Now imagine that one day, you do some profiling and realize that your application spends a lot of time inserting elements into the middle of "xy", and a LinkedList would be more efficient. How many lines of code would you have to change? Answer: maybe a lot. I don't know. You'd have to search.

Now, answer that again using "x". The answer is "one". That's good, yes?

This is even more important if those methods are in a library called by other people's code. Using an interface instead of a concrete class gives those people the flexibility to use whatever implementation is best for them.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Upcasting to the interface type "List" is preferred because it makes your code more flexible. Specifically, you can treat the object as a List in other code -- for example, passing it to a method that takes a List reference as an argument. This gives you the option of changing the runtime type later to some other List -- for example, if you decide that a LinkedList might be more appropriate -- and this won't break your other code because the object is still a "List."
 
Ganesh Gowtham
Ranch Hand
Posts: 225
IBM DB2 Eclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI u said type cating according to our need and for maintainence purpose,
we do have any advantage apart from that ?.
Pls suggest
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic