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.
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.
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.
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.
Saral Saxena wrote: . . . SO we must prefer set instead of add in some situations..?