This is more a Java in General or Beginning Java question. I know it is for the SCJD, because I had exactly the same question as you and you need it I guess for the find-method I googled around, found nothing appropriate and just wrote 4 lines of really impressive code to get the job done
senthil kumar. J wrote:Why don't you use toArrary() method provided by the List and pass list to an array.
Please note that this does not compile:
The Arrays.asList call is OK, the primitive ints will be autoboxed into Integer.
However, the signature of toArray is:
<T> T toArray(T a)
Here T must stand for a reference type, not a primitive.
Unfortunately, T is not related to E (Java does not allow type parameters to be bounded using super, so <T super E> T toArray(T a) is illegal), which means you can compile the following (obviously invalid) code:
Joined: Oct 15, 2009
Thank you for your excellent clarification Istvan!
Niclas Åstrand wrote:Is there a way, other than writing your own method, for converting a collection of say Long (List<Long>) to an array of long?
There's no other way in the standard classes included in the JDK, as far as I know. Of course third-party libraries may do it for you. The only one I know that has this is Guava - see Ints.toArray() for example. Wouldn't surprise me if there are others. Then again, this is a really simple method to write for yourself, so it's not worth putting a lot of effort into searching for other implementations.
Mike Simmons wrote:There's no other way in the standard classes included in the JDK, as far as I know. Of course third-party libraries may do it for you.
He asks this question with regard to SCJD certification, so use of 3rd party libraries are not allowed, only the JDK. So he will to code this on his own If Guava is open-source you can get the sources and have a look at the Ints.toArray() method for a bit of inspiration