The add(E ele) method of DelayQueue class in Java is used to insert the given element into the delay queue and returns true if the element has been successfully inserted. Here, E refers to the type of elements maintained by this DelayQueue collection.
Syntax:
public boolean add(E ele)
Parameters: This method takes only one parameter ele. It refers to the element which will be inserted into the delay queue.
Return Value: It returns a boolean value which is true if the element has been added successfully otherwise it returns false.
Exception:
- NullPointerException: This method throws a NullPointerException if a NULL is tried to inserted in this DelayQueue.
Below programs illustrate the add() method of DelayQueue class:
Program 1:
Java
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
DelayQueue<Delayed> queue = new DelayQueue<Delayed>();
Delayed obj = new Delayed() {
public long getDelay(TimeUnit unit)
{
return 24 ;
}
public int compareTo(Delayed o)
{
if (o.getDelay(TimeUnit.DAYS) > this .getDelay(TimeUnit.DAYS))
return 1 ;
else if (o.getDelay(TimeUnit.DAYS) == this .getDelay(TimeUnit.DAYS))
return 0 ;
return - 1 ;
}
};
queue.add(obj);
System.out.println( "Size of the queue : " + queue.size());
}
}
|
Output: Size of the queue : 1
Program 2: Program to demonstrate the NullPointerException.
Java
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class GFG {
public static void main(String args[])
{
DelayQueue<Delayed> queue = new DelayQueue<Delayed>();
try {
queue.add( null );
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output: java.lang.NullPointerException