I have to read a String
from console, so I used the tokenizer
to split it and add each token in a position on arrayList
, is there a way to improve the operation of split?
while ((currentLine = bufferedReader.readLine()) != null ) {
StringTokenizer string = new StringTokenizer(currentLine, " ");
while (string.hasMoreTokens()) {
arrayList.add(string.nextToken());
}
}
1 Answer 1
This is probably not your bottleneck, but you could achieve the same result by:
- ditching the
StringTokenizer
in favour ofString.split()
- replacing the
while
loop with a call toCollections.addAll(T...)
Like so:
while ((currentLine = bufferedReader.readLine()) != null) {
Collections.addAll(arrayList, currentLine.split(" ")));
}
The static method Collections.addAll()
is preferable to arrayList.addAll(Arrays.asList())
:
public static <T> boolean addAll(Collection<? super T> c, T... elements)
Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of
c.addAll(Arrays.asList(elements))
, but this method is likely to run significantly faster under most implementations.
-
\$\begingroup\$ I have my doubts whether this is more efficient since you first create a new
List<T>
after whichaddAll()
translates this back into an array usingtoArray()
. \$\endgroup\$Jeroen Vannevel– Jeroen Vannevel2014年06月09日 15:20:52 +00:00Commented Jun 9, 2014 at 15:20 -
\$\begingroup\$ @JeroenVannevel good point, although
asList
only creates a thin wrapper over the array. See the improved implementation above. \$\endgroup\$Adam– Adam2014年06月09日 23:35:15 +00:00Commented Jun 9, 2014 at 23:35