我有:

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);

09-04 15:13