簡體   English   中英

通用數組轉換

[英]Generic array casting

我有:

List<WatchEvent.Kind<Path>> events_kinds = new ArrayList<>();
events_kinds.add(StandardWatchEventKinds.ENTRY_DELETE);
events_kinds.add(StandardWatchEventKinds.ENTRY_CREATE);
events_kinds.add(StandardWatchEventKinds.ENTRY_MODIFY);

比我想使用register方法接受Kinds<?>[]類型作為第二個參數,所以我這樣做:

WatchKey key = path.register(watch_service, (WatchEvent.Kind<Path>[]) events_kinds.toArray());

但是當我執行代碼時,我有以下異常:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.nio.file.WatchEvent$Kind;

現在如何從該列表中獲取Kinds<?>[]數組?

謝謝。

您必須做:

WatchEvent.Kind[] eventsArray = events_kinds.toArray(new WatchEvent.Kind[0]);

根據Aditya的評論和更詳細的解釋:

給toArray(T [])方法提供的參數主要用於確定要創建哪種類型的數組,該數組將保存集合的元素。 最好傳入一個也具有必要大小的數組實例,以免讓該方法為您創建另一個數組實例。 從Javadoc:

//@param a the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
<T> T[] toArray(T[] a);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM