Method to extract data from a Set in Java

1

I am creating a method to extract values from a Set of clients , the values in question are the ID of all the clients present in the Set, the ID is obtained 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;
} 

By 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?

    
asked by Bryan Romero 11.11.2018 в 16:17
source

1 answer

1

As Jack the Ripper said, let's go in parts:

toArray ()

(Client[]) clients.toArray();

Object[] Set.toArray() returns a Object[] . Although all elements of Object[] are instances of Client , that is something that the JVM does not control so the casting fails. This method was before Java 5 so it was not possible to change the interface so that it will use generics since that would cause errors in the existing code.

The solution is to use the generics version of the method, which is T[] Set.toArray(T[] a) . You pass a Client[] (even if it's length 0 ) and it will return an instance of Client[] . If you already spend an array of the right size initially, it will return that same array.

So

clients.toArray(new Client[0]);

or even

clients.toArray(new Client[clients.size()]);

Of course, another option is to redefine the array so that it is Object[] and do the cast in for

Object[] arrayClients = (Object[]) clients.toArray();
...
for (int i = 0; i < arrayClients.length; i++) {
    clientIDs[i] = ((Client) arrayClients[i]).getClientID();
}

Iterable

But the best thing is that, like many collections, Set already implements Iterable , so you do not need the conversion to [] but you can use an enhanced for .

int i = 0;
for (Client client : clients) {
   clientsIDs[i] = client.getClientID();
   i++;
}

or the classic version (although I recommend the enhanced for ):

for(Iterator<Cliente> it = clients.iterator(); int i = 0; it.hasNext(); i++) {
    clientsIDs[i] = it.next().getClientID();
 }
    
answered by 11.11.2018 / 17:04
source