I am creating a method to extract values from a Client Set , the values in question are the IDs of all clients present in the Set, the ID is obtained by calling getClientID() .
My method:
public String[] extractIDsFromClientSet(Set<Client> clients) {
Client[] arrayClients = (Client[]) clients.toArray();
String[] clientIDs = new String[clients.size()];
for (int i = 0; i < arrayClients.length; i++) {
clientIDs[i] = arrayClients[i].getClientID();
}
return clientIDs;
}
When using my method I get the following exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lmodels.Client;
at view.userPanes.UserView.extractIDsFromClientSet(UserView.java:128)
at view.userPanes.UserView.setFieldData(UserView.java:82)
How do I correct my method?
As Jack the Ripper said, let's go by parts:
toArray()
Object[] Set.toArray()
returns aObject[]
. Although all the elements ofObject[]
are instances ofClient
, that is something the JVM does not control so the casting fails . This method was before Java 5 so you couldn't change the interface to use generics as that would cause errors in existing code.The solution is to use the generics version of the method, which is
T[] Set.toArray(T[] a)
. You pass it aClient[]
(even if it is of length0
) and it will return an instance ofClient[]
. If you already initially pass it an array of a suitable size, it will return that same array.So
or even
Of course, another option is to redefine the array to be
Object[]
and cast on thefor
iterable
But the best part is that, like many collections,
Set
it already implementsIterable
, so you don't need the cast to [] but can instead use an enhanced for .or the classic version (although I recommend the enhanced for ):