2012-10-12 74 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