java - Is it better to use a TreeSet or ArrayList when using a custom comparator -



java - Is it better to use a TreeSet or ArrayList when using a custom comparator -

i have implemented graph. want sort given subset of vertices respect degrees. therefore, i've written custom comparator named degreecomparator.

private class degreecomparator implements comparator<integer> { @override public int compare(integer arg0, integer arg1) { if(adj[arg1].size() == adj[arg0].size()) homecoming arg1 - arg0; else homecoming adj[arg1].size() - adj[arg0].size()); } }

so, 1 of below more efficient?

using treeset

public collection<integer> sort(collection<integer> unsorted) { set<integer> sorted = new treeset<integer>(new degreecomparator()); sorted.addall(unsorted); homecoming sorted; }

using arraylist

collections.sort(unsorted, new degreecomparator());

notice sec approach not function, one-line code.

intuitively, i'd rather take sec one. i'm not sure if more efficient.

a treeset set. removes duplicates (elements same degree). both aren't equivalent.

anyway, if want naturally sorted list, sort list. work whether collection has duplicates or not, , if has same complexity (o(n*log(n)) populating treeset, faster (because has move elements in array, instead of having create lots of tree nodes).

java performance sorting arraylist set

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -