Java ArrayList -> Array

Wingy

[H]ard|Gawd
Joined
Dec 18, 2000
Messages
1,294
Hello,
I'm trying to use URLClassLoader, and to do that I need to take an existing ArrayList<URL> that I have and convert it to URL[].

This can be done simply like this:
URLClassLoader remoteClassLoader = new URLClassLoader (remoteRepositories.toArray (new URL[remoteRepositories.size ()]));

I don't understand exactly why I have to pass an array into remoteRepository.toArray(). When I look at the documentation, it says the array passed in is the array in which the list is stored. However, the function also returns an array.

So does this mean if I did this:

URL[] a = new URL[10];
URL[] a2 = remoteRepositories.toArray(a);

Does this mean a and a2 are the exact same reference now? Can somebody explain to me why this function is implemented in such a way?
 
I think you might be overlooking something...
ArrayList has a parameterless .toArray() function.
URLClassLoader remoteClassLoader = new URLClassLoader(remoteRepositories.toArray(new URL[remoteRepositories.size ()]));
reduces to
URLClassLoader remoteClassLoader = new URLClassLoader(remoteRepositories.toArray();
 
I don't understand exactly why I have to pass an array into remoteRepository.toArray(). When I look at the documentation, it says the array passed in is the array in which the list is stored. However, the function also returns an array.

You don't. There are 2 toArray methods, one takes an array and the other doesn't.

Does this mean a and a2 are the exact same reference now? Can somebody explain to me why this function is implemented in such a way?

Yes, if you change a[0] = "Something cool" a2[0] will = "Something cool" also.
 
You have to pass it an array because because the URLClassLoader requires a specific type of Array. The URLClassLoader takes an array of URL, not an array of Object.

If you look at the documentation of toArray, you will see that the toArray with zero arguments returns an array of type Object[]. However, the toArray method that takes an array returns an array of that specific type.


URL[] urls = (URL[]) list.toArray() <-- ClassCastException, because list.toArray() returns an Object[], not URL[].

vs.

URL[] urls = (URL[]) list.toArray(new URL[0]); <-- works
 
Your fist line worked for me.

My question was, why does that constructor have the other version with the array passing in. The doc says it stores the result in that array. But at the same time, it returns an array. I just couldn't figure out the purpose.
 
The document says it returns an array of the same type passed in populated with the elements of the List. It doesn't necessarily use the same array (for example, if the input array is too small, it will create one at runtime of the same type that can accommodate the correct number of items). That is why it returns an array.
 
Back
Top