• Post Reply Bookmark Topic Watch Topic
  • New Topic

advantage of declaring list  RSS feed

 
sam liya
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1) ArrayList myList = new ArrayList();

2) List myList = new ArrayList();

we can declare an arrayList as these two ways .
1) what are the benifit of these two ways.
2) is this both ways are same or not?
 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To achieve polymorphism. Your myList won't be tied to the implementation. If suppose you want to change the implementation of ArrayList() to something else, you can do it easily using the first approach.

 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In writing this way, if you later decide that instead of ArrayList, LinkedList would perform better in the application then you just have to change a single line of code and everything would still work correctly.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Muhammad Ali Khojaye wrote:In writing this way, if you later decide that instead of ArrayList, LinkedList would perform better in the application then you just have to change a single line of code and everything would still work correctly.


Also... if you want to use it in threaded fashion, you can "change a single line of code" to get it from Collections.synchronizedList(). Of course, in that case, you have to use the List interface, as the class files for the sychronization list wrappers are not in scope, out of the Collections class.

Henry
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is just my PERSONAL opinion, but...

When you're writing all the code yourself, and writing rather simple programs, I don't see the advantage. The real power comes in when someone else uses your code. You provide them a method they can call to get an object they want to use. if you tell them to expect an ArrayList, then you are locked into always using an ArrayList.

However, if you tell them to expect a List, you can change your code to return anything, any time you want, as long as it's still a List.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!