Open In App

Java Collections checkedQueue() Method with Examples

Last Updated : 03 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Java Program to Create a  
// type-safe view of the List  
// using checkedQueue() Method
  
import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create a queue
        Queue<String> data = new PriorityQueue<String>();
        
        // add elements
        data.add("Python");
        data.add("R");
        data.add("C");
        data.add("Java/jsp");
        
        // Create type safe view of the List
        System.out.println(
            Collections.checkedQueue(data, String.class));
    }
}


Output

[C, Java/jsp, Python, R]

Example 2:

Java




import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create a queue
        Queue<Integer> data = new PriorityQueue<Integer>();
  
        // add elements
        data.add(1);
        data.add(23);
        data.add(56);
        data.add(21);
  
        // Create type safe view of the List
        System.out.println(
            Collections.checkedQueue(data, Integer.class));
    }
}


Output

[1, 21, 56, 23]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads