我想将LinkedList
转换为arrayList
Date dataInizio = new Date();
LinkedList<Node> queue = new LinkedList<Node>();
int n = combinazioni.size();
ArrayList<Elemento> temp = new ArrayList<Elemento>();
temp.add(combinazioni.get(0));
queue.add(new Node(0, temp));
// add all different integers to the queue once.
for (int i = 1; i < n; ++i) {
if (combinazioni.get(i - 1) == combinazioni.get(i)) {
continue;
}
temp = new ArrayList<Elemento>();
temp.add(combinazioni.get(i));
queue.add(new Node(i, temp));
}
// do bfs until we have no elements
while (!queue.isEmpty()) {
Node node = queue.remove();
if (node.lastIndex + 1 < n) {
Node newNode = new Node(node);
newNode.lastIndex = node.lastIndex + 1;
newNode.currentList.add(combinazioni.get(node.lastIndex + 1));
queue.add(newNode);
}
for (int i = node.lastIndex + 2; i < n; ++i) {
if (combinazioni.get(i - 1) == combinazioni.get(i)) {
continue;
}
// create a copy and add extra integer
Node newNode = new Node(node);
newNode.lastIndex = i;
newNode.currentList.add(combinazioni.get(i));
queue.add(newNode);
}
GestoreRegole gestoreRegole = new GestoreRegole();
gestoreRegole.esegui(node.currentList);
}
Date dataF = new Date();
long tempo = dataF.getTime() - dataInizio.getTime();
logger.info("durata genera combinazioni: " + tempo);
}
答案 0 :(得分:1)
Java中的大多数集合都有一个构造函数,它接受兼容的集合并生成新类型的副本:
LinkedList<T> oldList;
ArrayList<T> newList = new ArrayList<>(oldList);
相当于:
LinkedList<T> oldList;
ArrayList<T> newList = new ArrayList<>();
//Optional: newList.ensureCapacity(oldList.size());
newList.addAll(oldList);
相当于:
LinkedList<T> oldList;
ArrayList<T> newList = new ArrayList<>();
//Optional: newList.ensureCapacity(oldList.size());
for (T element: oldList) {
newList.add(element);
}
请注意,所有这些都具有O(n)时间和空间复杂性,因为您实际上是在创建列表内容的新副本。由于LinkedList和ArrayList具有不同的结构,因此无法解决此问题。使用上述方法之一也可以加速代码访问.get(i)在LinkedList上具有线性时间,而这些都使用迭代器,将初始化成本从O(n ^ 2)按照代码减少到O(n) )。
您似乎在重复删除重复项目时付出了很多努力。 Peraphs a Set系列对您的用例来说是更好的选择吗?