Why are there two add methods in LinkedList?

Posted on 2011-10-25
Last Modified: 2012-05-12
In lines 39 through 49 of the Java code below, I can understand why there is an add method with a void return type, but why is there another add method with a boolean return type? The first add method seems to be accessing the second add method, which simply adds a node before a specified index, right? Why doesn't this class just have one add method to keep things simple?
public class MyLinkedList<AnyType> implements Iterable<AnyType> {

	private int theSize;
	private int modCount = 0;
	private Node<AnyType> beginMarker;
	private Node<AnyType> endMarker;

	private static class Node<AnyType> 
		public Node( AnyType d, Node<AnyType> p, Node<AnyType> n ) {
			data = d; prev = p; next = n;}

		public AnyType data; 
		public Node<AnyType>  prev;
		public Node<AnyType>  next;

	public MyLinkedList( ) {
		clear( );}

	public void clear( ) // Change the size of this collection to zero.
		beginMarker = new Node<AnyType>( null, null, null ); 
		endMarker = new Node<AnyType>( null, beginMarker, null ); = endMarker;

		theSize = 0;

	public int size( ) { //Returns the number of items in this collection.
		return theSize; 

	public boolean isEmpty( ) { 
		return size( ) == 0;} // test to see if this is true

	public boolean add( AnyType x ) { //Adds an item to this collection, at the end
		add( size( ), x );
		return true;

	/* the add method adds an item to this collection, at specified position. 
         Items at or after that 	position are slid one position higher */

	public void add( int idx, AnyType x ) {
		addBefore( getNode( idx), x );}

	public AnyType get( int idx ) { // Returns the item at position idx
		return getNode( idx ).data;}

	public AnyType set( int idx, AnyType newVal ) { //Changes the item at position idx
		Node<AnyType> p = getNode( idx );
		AnyType oldVal =; = newVal; 
		return oldVal;

	public AnyType remove( int idx ) { //Removes an item from this collection
		return	remove(getNode( idx ));}

	/* this addBefore method adds an item to this collection, at specified position p. 
	Items at or after that position are slid one position higher */

	private void addBefore( Node<AnyType> p, AnyType x ) {
		Node<AnyType> newNode = new Node<AnyType>( x, p.prev, p ); = newNode; 
		p.prev = newNode; 

	private AnyType remove( Node<AnyType> p ) {  // Removes the object contained in Node p. = p.prev; =; 

	private Node<AnyType> getNode( int idx)
		Node<AnyType> p;
		if( idx < 0 || idx > size() )
            throw new IndexOutOfBoundsException();
        if( idx < size( ) / 2 ) {
            p =;
            for( int i = 0; i < idx; i++ )
                p =;            
            p = endMarker;
            for( int i = size( ); i > idx; i-- )
                p = p.prev;
		return p;

	public java.util.Iterator<AnyType> iterator( ) {
        return new LinkedListIterator( );

	private class LinkedListIterator implements java.util.Iterator<AnyType>
		private Node<AnyType> current =;
       private int expectedModCount = modCount; 
		private boolean okToRemove = false;
		public boolean hasNext( ) {
			return current != endMarker;
        public AnyType next( )
            if( modCount != expectedModCount )
                throw new java.util.ConcurrentModificationException( ); 
            if( !hasNext( ) )
                throw new java.util.NoSuchElementException( ); 
            AnyType nextItem =;
            current =;
            okToRemove = true;
            return nextItem;
        public void remove( )
            if( modCount != expectedModCount )
                throw new java.util.ConcurrentModificationException( ); 
            if( !okToRemove )
                throw new IllegalStateException( );
            MyLinkedList.this.remove( current.prev );
            okToRemove = false;  

Open in new window

Question by:shampouya
    LVL 84

    Accepted Solution

    one adds at a specified positionthe other adds at the end
    LVL 16

    Expert Comment

    In the case of the one that adds to the end, no return code is needed... the list always has an end.  But if you request to add at a specific position, the position might not exist, therefore the function needs to be able to report back the failure.
    LVL 37

    Assisted Solution

    The reason to have both add functions is to increase the usefulness of the code for the person using the code later.
    If you wanted to add something to the end of the list you could just use the second one, but it's easier to just say add(x) and it by default adds it to the end. Most of the time when you are using a list, this is where you add things anyway.

    You'll also notice that the second add function calls the addBefore function which is private. The users of the code could all just use that function but the code writer has made it private and given the users the other functions since they are easier to use and safer.
    LVL 32

    Assisted Solution

    to add to above.

    the main difference is not the boolean return type (which doesn't actually make much sense as it is always true) but the additional position argument.  

    normally, the second function would be called 'insert' or 'insert_before' and not 'add'. if you look at the implementation of the second add function you see they called private 'addBefore' which has a Node<anyType> as first argument. so the three add functions have different level of complexity and only the first two are for public use.

    LVL 32

    Expert Comment

    sorry TommySzalapski, i repeated some of your remarks cause i tooks me some time to submit.


    Author Closing Comment

    thanks everybody

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Enabling OSINT in Activity Based Intelligence

    Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

    Suggested Solutions

    Title # Comments Views Activity
    matchUp  challenge 6 35
    Enhanced For loop vs ForEach Loop 4 42
    WMI, model #, retrieving information 10 52
    word0 challenge 4 37
    Article by: Nadia
    Suppose you use Uber application as a rider and you request a ride to go from one place to another. Your driver just arrived at the parking lot of your place. The only thing you know about the ride is the license plate number. How do you find your U…
    Iteration: Iteration is repetition of a process. A student who goes to school repeats the process of going to school everyday until graduation. We go to grocery store at least once or twice a month to buy products. We repeat this process every mont…
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now