Java Collections 的 checkedQueue() 方法是一種返回給定隊列的動態和類型安全視圖的方法。任何插入錯誤類型元素的嘗試都將立即導致 ClassCastException。
用法:
public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type)
參數:
- queue是為動態安全而返回的隊列
- type是隊列元素的數據類型
返回類型:此方法將返回給定隊列的動態且類型安全的視圖。
異常:
- ClassCastException:ClassCastException 是當我們試圖將一個類從一種類型不正確地轉換為另一種類型時在 Java 中引發的運行時異常。
範例1:使用 checkedQueue() 方法創建 List 的 type-safe 視圖
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));
}
}
輸出
[C, Java/jsp, Python, R]
範例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));
}
}
輸出
[1, 21, 56, 23]
相關用法
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java.util.Collections.frequency()用法及代碼示例
- Java Collections.reverse()用法及代碼示例
- Java Collections.shuffle()用法及代碼示例
- Java Collections singletonMap()用法及代碼示例
- Java Collections min()用法及代碼示例
- Java Collections max()用法及代碼示例
- Java Collections addAll()用法及代碼示例
- Java Collections asLifoQueue()用法及代碼示例
- Java Collections unmodifiableCollection()用法及代碼示例
- Java Collections unmodifiableSortedMap()用法及代碼示例
- Java Collections unmodifiableSet()用法及代碼示例
- Java Collections unmodifiableMap()用法及代碼示例
- Java Collections unmodifiableList()用法及代碼示例
- Java Collections checkedCollection()用法及代碼示例
- Java Collections checkedSet()用法及代碼示例
- Java Collections checkedSortedMap()用法及代碼示例
- Java Collections checkedSortedSet()用法及代碼示例
- Java Collections enumeration()用法及代碼示例
- Java Collections copy()用法及代碼示例
- Java Collections fill()用法及代碼示例
- Java Collections indexOfSubList()用法及代碼示例
注:本文由純淨天空篩選整理自sireeshakanneganti112大神的英文原創作品 Java Collections checkedQueue() Method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。