Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
DiSL
DiSL
Commits
d7100653
Commit
d7100653
authored
May 14, 2014
by
Lubomir Bulej
Browse files
Lists.java: Avoid reallocations when creating an ArrayList from collections.
parent
b298acab
Changes
1
Show whitespace changes
Inline
Side-by-side
src-util/ch/usi/dag/util/Lists.java
View file @
d7100653
...
@@ -2,6 +2,7 @@ package ch.usi.dag.util;
...
@@ -2,6 +2,7 @@ package ch.usi.dag.util;
import
java.util.ArrayList
;
import
java.util.ArrayList
;
import
java.util.Collection
;
import
java.util.Collection
;
import
java.util.Collections
;
import
java.util.LinkedList
;
import
java.util.LinkedList
;
import
java.util.List
;
import
java.util.List
;
...
@@ -142,20 +143,29 @@ public final class Lists {
...
@@ -142,20 +143,29 @@ public final class Lists {
//
//
final
int
collectionCount
=
collections
.
length
;
final
int
collectionCount
=
collections
.
length
;
if
(
collectionCount
>=
1
)
{
if
(
collectionCount
>
0
)
{
final
ArrayList
<
E
>
result
=
new
ArrayList
<
E
>
(
collections
[
0
]);
//
for
(
int
i
=
1
;
i
<
collectionCount
;
i
++)
{
// Aggregate collection sizes to determine the size of the
result
.
addAll
(
collections
[
i
]);
// resulting ArrayList to avoid reallocations, then gather
// all elements from the collections.
//
int
elementCount
=
0
;
for
(
final
Collection
<?
extends
E
>
collection
:
collections
)
{
elementCount
+=
collection
.
size
();
}
final
ArrayList
<
E
>
result
=
new
ArrayList
<
E
>
(
elementCount
);
for
(
final
Collection
<?
extends
E
>
collection
:
collections
)
{
result
.
addAll
(
collection
);
}
}
return
result
;
return
result
;
}
else
{
}
else
{
return
new
ArrayList
<
E
>
(
0
);
return
Collections
.
emptyList
(
);
}
}
}
}
/* ***********************************************************************
/* ***********************************************************************
* LinkedList
* LinkedList
* ***********************************************************************/
* ***********************************************************************/
...
...
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment