0

When it comes to the inserting, iterating or even sorting, and there's a huge number of items to be managed, what is it more efficient in Java?

Is using primitive types arrays the best alternative?
Does ArrayList become best alternative?
When is it better to go for LinkedList?

diegoaguilar
  • 8,179
  • 14
  • 80
  • 129
  • Is this for plain curiosity? If not, please post your functional requirement to get accurate help. Otherwise, I would recommend using `List yourList = new ArrayList();`, work with it and use a profiler to see if this generates memory/performance issues to change it by another implementation. – Luiggi Mendoza Nov 20 '13 at 19:40
  • Possible duplicate of http://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist – Piovezan Nov 20 '13 at 19:43
  • possible duplicate of [Big-O summary for Java Collections Framework implementations?](http://stackoverflow.com/questions/559839/big-o-summary-for-java-collections-framework-implementations) – Laf Nov 20 '13 at 19:46

3 Answers3

0

It depends on the number of actions you make with each type operation. For example if you only use sorting 1% of the amount of actions then you don't need worry about it. same for insert.

milonimrod
  • 306
  • 2
  • 3
0

There are no something like "the best collection for everything". Iterating (using iterator) is more or less comparable in ArrayList, LinkedList and regular array. For intensive inserting/removing elements LinkedList is the best choice. Efficiency of sorting depends on used algorithm. Anyway, remember that random access is really slow in LinkedList, so sorting may be slow as well.

gaczm
  • 75
  • 5
0

Is using primitive types arrays the best alternative?

A primitive array is the best option if you have a collection of primitives. If you want Objects, you can't easily use primitive arrays.

Does ArrayList become best alternative?

If you have objects yes, provided you are inserting at the end.. Lists are ordered but not sorted.

A TreeSet is sorted as you add entries, which might be more desirable.

When is it better to go for LinkedList?

If you want to insert in random places, this is better.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 2
    The "insert anywhere" argument is weaker than its frequent use suggests: You can only insert efficiently if you already have a reference to the right node, but in many cases you either can't have that or it'd be a huge pain to carry this reference around and maintain it. And the constant factors mean it's only really faster than random insertion for array(list)s for surprisingly large data sets. –  Nov 20 '13 at 19:49