| Author |
difference between set and add method of list interface
|
ajay mittal
Greenhorn
Joined: Nov 23, 2011
Posts: 23
|
|
Hi all,
I have a doubt regarding List interface in collection. There are two methods provided in the List interface.
E set(int index, E element);
void add(int index, E element);
The difference which i can point out is set returns the element while add do not.
Can anyone help me out to differentiate among these two and when to use which one.
regards,
Ajay Mittal
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
|
set replaces the element at the given index. add inserts the element at the given index and moves all elements ahead of it one position.
|
Joanne
|
 |
ajay mittal
Greenhorn
Joined: Nov 23, 2011
Posts: 23
|
|
Joanne Neal wrote:set replaces the element at the given index. add inserts the element at the given index and moves all elements ahead of it one position.
Thanks dear
Ajay
|
 |
Saral Saxena
Ranch Hand
Joined: Apr 22, 2011
Posts: 202
|
|
Joanne Neal wrote:set replaces the element at the given index. add inserts the element at the given index and moves all elements ahead of it one position.
Hi Joanne,
SO we must prefer set instead of add in some situations..?
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16479
|
|
Saral Saxena wrote:
Joanne Neal wrote:set replaces the element at the given index. add inserts the element at the given index and moves all elements ahead of it one position.
SO we must prefer set instead of add in some situations..?
Well, yes. Perhaps it isn't immediately obvious... but if you want to replace a particular element, then you should prefer the "set" method. Whereas if you want to insert an element, then you should prefer the "add" method.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
Saral Saxena wrote:SO we must prefer set instead of add in some situations..?
That totally depends on what your program needs to do. Ofcourse in some situations you would need to use set, and in other situations you would need to use add. Without knowing what your program is supposed to do, it is impossible to know which of those is appropriate to use.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32599
|
|
Saral Saxena wrote: . . . SO we must prefer set instead of add in some situations..?
Yes, just as we prefer a car to a boat in some situations and a boat to a car in other situations. You use a car or a boat if you are going to different places. You use set and add because you are doing different things.
|
 |
 |
|
|
subject: difference between set and add method of list interface
|
|
|