Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes List and ArrayList  Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "List and ArrayList  Problem" Watch "List and ArrayList  Problem" New topic

List and ArrayList Problem

Ganesh Gowtham
Ranch Hand

Joined: Mar 30, 2005
Posts: 225

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

Thanks, Ganesh Gowtham
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

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.

[Jess in Action][AskingGoodQuestions]
marc weber

Joined: Aug 31, 2004
Posts: 11343

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."

"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
Ganesh Gowtham
Ranch Hand

Joined: Mar 30, 2005
Posts: 225

HI u said type cating according to our need and for maintainence purpose,
we do have any advantage apart from that ?.
Pls suggest
I agree. Here's the link:
subject: List and ArrayList Problem
jQuery in Action, 3rd edition