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.
Method | Interface | Returns | Exception | When to Use |
---|---|---|---|---|
add(e) | List | boolean | IllegalStateException if the list is full | Using the LinkedList as a List to check if the element was successfully added |
offer(e) | Queue | boolean | boolean false if the queue is full | Using LinkedList as a Queue or for interchanging implementations of the Queue interface |
Facing issues? Have Questions? Post them here! I am happy to answer!
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
- Fix Error Code: 80090030 in Microsoft Outlook/Teams - Microsoft
- Java 8 Streams map() with examples - Java
- How to save All Files at once in Notepad++ - NotepadPlusPlus
- jQuery : Move to top of the page - jQuery
- PHP Fatal error : Call to a member function bind_param() on a non-object - PHP
- Find Duplicate Files using Mac Terminal Command - MacOS
- Bash How to Save Output of a Command to a Variable - Bash
- 30+ Zoom video communications application shortcuts for macOS - MacOS