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<?>[]从该列表中获取数组?

谢谢。

4

1 回答 1

1

你必须这样做:

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);
于 2012-10-12T14:55:28.213 回答