I have a Linked List object called ll
. I added some data into that object. Assume that are like following:
LinkedList ll = new LinkedList();
ll.add("Mohan");
ll.add("Rajesh");
ll.addFirst("Kumar");
ll.addLast("Nammu");
ll.add("Divyesh");
My question is: if I already inserted 100 data, when I use addFirst()
method then that data will be insert at First, but the same functionality should happen for addLast()
method also, which means if anywhere i use addLast()
method also it has to insert data at last, but if I add any more data after addLast()
method that data only inserting at last then what is the use of addLast()
method instead of that we can use just add() method only right ?
LinkedList
class implements both Deque
and Queue
interface. It inherits add(E)
method from Queue
, and addLast(E)
method from Deque
. Both the methods have same functionality.
As the javadoc states, addLast
and add
are equivalent: addLast(E e)
javap java.util.LinkedList
Compiled from "LinkedList.java"
public class java.util.LinkedList extends java.util.AbstractSequentialList implements java.util.List, java.util.Deque, java.lang.Cloneable, java.io.Serializable {
you can see here that LinkedList extends AbstractSequentialList and it implements list interface, add and remove are the methods from this interface you can check it with the following command
javap java.util.List
Compiled from "List.java"
public interface java.util.List extends java.util.Collection {
public abstract int size();
public abstract boolean isEmpty();
public abstract boolean contains(java.lang.Object);
public abstract java.util.Iterator iterator();
public abstract java.lang.Object[] toArray();
public abstract T[] toArray(T[]);
public abstract boolean add(E);
public abstract boolean remove(java.lang.Object);
public abstract boolean containsAll(java.util.Collection);
public abstract boolean addAll(java.util.Collection);
public abstract boolean addAll(int, java.util.Collection);
public abstract boolean removeAll(java.util.Collection);
public abstract boolean retainAll(java.util.Collection);
public void replaceAll(java.util.function.UnaryOperator);
public void sort(java.util.Comparator);
public abstract void clear();
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
public abstract E get(int);
public abstract E set(int, E);
public abstract void add(int, E);
public abstract E remove(int);
public abstract int indexOf(java.lang.Object);
public abstract int lastIndexOf(java.lang.Object);
public abstract java.util.ListIterator listIterator();
public abstract java.util.ListIterator listIterator(int);
public abstract java.util.List subList(int, int);
public java.util.Spliterator spliterator();
}
actually the method add and addLast does the same thing but because of the above reason It have both methods.
I think I have given the answer. feel free to comment...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With