java - Convert linked list in arrayList -
i want convert 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 different integers queue once. (int = 1; < 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)); } // bfs until 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); } (int = node.lastindex + 2; < n; ++i) { if (combinazioni.get(i - 1) == combinazioni.get(i)) { continue; } // create copy , add 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); }
most of collections in java have constructor takes compatible collection , generates copy of new type:
linkedlist<t> oldlist; arraylist<t> newlist = new arraylist<>(oldlist); which equivalent to:
linkedlist<t> oldlist; arraylist<t> newlist = new arraylist<>(); //optional: newlist.ensurecapacity(oldlist.size()); newlist.addall(oldlist); which equivalent to:
linkedlist<t> oldlist; arraylist<t> newlist = new arraylist<>(); //optional: newlist.ensurecapacity(oldlist.size()); (t element: oldlist) { newlist.add(element); } note these have o(n) time , space complexity, creating new copy of list content. there no way around linkedlist , arraylist have different structures. using 1 of approaches above speed code accessing .get(i) on linkedlist has linear time, while these use iterators, reducing initialization cost o(n^2) per code o(n).
you seem put lot on emphasys on removing duplicates. peraphs set collection better option use case?
Comments
Post a Comment