Question

I have to add an element at the end of a list so now I am using addLast() function of LinkedList to add element at the end. It does add element in the list if and only if there is NO more add() statements after it.

Below works fine.

LinkedList<String> ls = new LinkedList<String>();

    ls.add("C");
    ls.add("E");
    ls.add("D");
    ls.add("B");

    ls.addLast("F");            
    ls.addFirst("A");

    for( String l : ls )             
          System.out.println( l  );

And in the below case, it will not add item at the end of the list.

LinkedList<String> ls = new LinkedList<String>();

    ls.add("C");
    ls.add("E");
    ls.add("D");

    ls.addLast("F"); 
    ls.add("B");

    ls.addFirst("A");

    for( String l : ls )             
          System.out.println( l  );

However, addFirst() works fine regardless of place where you call it.

How I can achieve this? any suggestion please.

Was it helpful?

Solution

From java docs:

public boolean add(E e)
Appends the specified element to the end of this list.
This method is equivalent to addLast(E).

Specified by:
add in interface Collection<E>
Specified by:
add in interface Deque<E>
Specified by:
add in interface List<E>
Specified by:
add in interface Queue<E>
Overrides:
add in class AbstractList<E>
Parameters:
e - element to be appended to this list
Returns:
true (as specified by Collection.add(E))

In your case the you add 'B' for the end of the list after you added 'F' to the end of the list

OTHER TIPS

"it will not add item at the end of the list."

Yes it will, it adds the item at the end of the current list. What it won't do is keep it always last. Imagine what would happen if you did addLast() two times, which one would have priority? Same thing with addFirst(), it only works on the current list, and if you add more firsts the other ones won't be first anymore.

Specify the position of adding "B" for example ls.add(ls.size() - 1, "B"); Then "F" will be added in last.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top