Commit d7100653 authored by Lubomir Bulej's avatar Lubomir Bulej
Browse files

Lists.java: Avoid reallocations when creating an ArrayList from collections.

parent b298acab
...@@ -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
* ***********************************************************************/ * ***********************************************************************/
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment