Java: LinkedList offer vs add methods


The LinkedList class in Java provides two methods offer and add to add an element to the list.

There is a subtle difference between both of them.


The add method

    The add method is inherited from the List interface. It returns a boolean value to indicate whether the element was successfully added to the list or not.

    Also, you will get an IllegalStateException if the list is at its capacity.


The offer method

    The offer method is defined in the Queue Interface. It was added to the Queue interface in Java 1.5

    It returns a boolean value indicating whether the element was successfully added to the queue or not.

    offer method will return a boolean false if the queue is at its capacity instead of an exception.



MethodInterfaceReturnsExceptionWhen to Use
add(e)ListbooleanIllegalStateException if the list is fullUsing the LinkedList as a List to check if the element was successfully added
offer(e)Queuebooleanboolean false if the queue is fullUsing LinkedList as a Queue or for interchanging implementations of the Queue interface

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap