Java Collections checkedQueue() Method with Examples
Last Updated :
03 Jan, 2022
The checkedQueue() method of Java Collections is a method that returns a dynamically and typesafe view of the given Queue. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException.
Syntax:
public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type)
Parameters:
- queue is the queue that is returned for dynamically safe
- type is the data type of the queue elements
Return Type: This method will return the dynamically and typesafe view of the given Queue.
Exceptions:
- ClassCastException: ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another.
Example 1: Create a type-safe view of the List using checkedQueue() Method
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Queue<String> data = new PriorityQueue<String>();
data.add( "Python" );
data.add( "R" );
data.add( "C" );
data.add( "Java/jsp" );
System.out.println(
Collections.checkedQueue(data, String. class ));
}
}
|
Output
[C, Java/jsp, Python, R]
Example 2:
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Queue<Integer> data = new PriorityQueue<Integer>();
data.add( 1 );
data.add( 23 );
data.add( 56 );
data.add( 21 );
System.out.println(
Collections.checkedQueue(data, Integer. class ));
}
}
|
Share your thoughts in the comments
Please Login to comment...