从ArrayList中长[] [英] From arrayList to long[]

查看:103
本文介绍了从ArrayList中长[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样做,需要返回长[]的方法。它看起来是这样的:

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

public long[] parseString(String input)

输入像字符串:


  • 1,3,4

  • 10,30,40,50

里面parseString我使用正则表达式来获取所有号码,并将其添加到一个ArrayList,因为我不知道它有多少oconcurrences找到。

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.

最后我创造一个长[]与ArrayList的大小,做一个对每个将其添加到漫长的[]变种。

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++;

,然后用大小创建一个长[尺寸大小],并做了:
matcher.reset(),现在保存在漫长的[]可变长的值。

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.

你认为哪这是最好的?

有没有更好的方法来做到这一点?

Is there a better way to do this?

记住我不能改变方法签名:(

Remember I can't change the method signature :(

推荐答案

由于Java中的基本类型和对象之间的二分法,你不能使用泛型列表列表<龙> .toArray(长[])来建立一个基本数组作为结果。有可以使用原始的集合,但无论哪种方式 - 使用列表或以上组的工作 - 你从一个临时存储的数据复制到一个基本数组

Because of the dichotomy between primitives and objects in Java, you can't use the generic list List<Long>.toArray(Long[]) to build a primitive array as the result. There are primitive collections which can be used, but either way - using a list or working over the groups - you're copying data from a temporary storage to a primitive array.

因此​​,无论你建议的方式大约是对方的好。如果它的性能敏感,轮廓都和选​​择最适合您的正则表达式。

So either of the ways you suggest is about as good as each other. If it's performance sensitive, profile both and choose the best for your regex.

这篇关于从ArrayList中长[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆