Java Collections 的 checkedQueue() 方法是一種返回給定 Set 的動態且類型安全的視圖的方法。任何插入錯誤類型元素的嘗試都將立即導致 ClassCastException。
用法:
public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> set, Class<E> datatype)
參數:
- set是輸入集數據
- datatype是 set 可以容納的元素類型
返回類型:此方法將返回給定 Set 的動態且類型安全的視圖。
異常:
- ClassCastException:ClassCastException 是當我們試圖將一個類從一種類型不正確地轉換為另一種類型時在 Java 中引發的運行時異常。
範例1:
Java
// Java program to create a Tree set and
// display the elements in a typesafe way
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create a set of string type
NavigableSet<String> data = new TreeSet<>();
// Insert the values into the set
data.add("java");
data.add("php/jsp");
data.add("python");
data.add("R");
// type safe view of the set
System.out.println(Collections.checkedNavigableSet(
data, String.class));
}
}
輸出
[R, java, php/jsp, python]
範例2:
Java
// Java program to create a Tree set and
// display the elements in a typesafe way
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create a set of string type
NavigableSet<Integer> data = new TreeSet<>();
// Insert the values into the set
data.add(1);
data.add(2);
data.add(3);
data.add(4);
// type safe view of the set
System.out.println(Collections.checkedNavigableSet(
data, Integer.class));
}
}
輸出
[1, 2, 3, 4]
相關用法
- 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 checkedNavigableSet() Method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。