Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From arrayList to long[]

I am doing a method that needs to return a long[]. It looks like this:

public long[] parseString(String input)

input are strings like:

  • 1, 3, 4
  • 10, 30, 40, 50

Inside parseString I use a regex to get all numbers and add them to an ArrayList as I can't know how many oconcurrences it will find.

At the end I create a long[] with the size of the arrayList and do a for each to add it to the long[] var.

Another way would be: First count every occurrence with a

while ( matcher.find() ) size++;

and then with size create a long[] of size size and do a: matcher.reset() and now save the long values in the long[] variable.

Which do you think it's the best?

Is there a better way to do this?

Remember I can't change the method signature :(

like image 1000
Macarse Avatar asked Nov 08 '09 14:11

Macarse


1 Answers

At the risk of being a huge pimp for Google's guava-libraries (I really do love it!), the Longs class makes this a one-liner:

return Longs.toArray(foundLongs);

ta-daa!

like image 155
Cowan Avatar answered Oct 09 '22 23:10

Cowan