2012-10-12 75 views
0

我有:通用陣列鑄造

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<?>[]數組嗎?

謝謝。

回答

1

你必須做到:

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

按阿迪亞的評論和更詳細的解釋:

給予的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); 
+1

不應它是'WatchEvent.Kind [] eventsArray = events_kinds.toArray(新WatchEvent.Kind [events_kinds.size()]);'? –

+0

@Aditya +1不是絕對必要的,但一個更好的方法,謝謝你的修正 –

+0

@Shivan非常感謝它的工作! – xdevel2000