0

I've:

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

than I want to use the register method that accepts as second arguments a Kinds<?>[] type and so I do:

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

but when I execute the code I have the following exception:

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

Now how can I get a Kinds<?>[] array from that list?

Thanks.

1 Answer 1

1

You must do:

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

As per Aditya's comment and as a more detailed explanation:

The argument given to the toArray(T[]) method is mainly used to determine what type of array to create that will hold the collection's elements. It is how ever better to pass in an array instance that also has the necessary size, to avoid having the method create another array instance for you. From the 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); 
Sign up to request clarification or add additional context in comments.

2 Comments

shouldn't it be WatchEvent.Kind[] eventsArray = events_kinds.toArray(new WatchEvent.Kind[events_kinds.size()]); ?
@Aditya +1 Not strictly necessary, but a better approach, thanks for the correction

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.