I want to use data structure that needs to be sorted every now and again. The size of the data structure will hardly exceed 1000 items.
Which one is better - ArrayList
or LinkedList
?
Which sorting algorithm is better to use?
I want to use data structure that needs to be sorted every now and again. The size of the data structure will hardly exceed 1000 items.
Which one is better - ArrayList
or LinkedList
?
Which sorting algorithm is better to use?
Up to Java 7, it made no difference because Collections.sort
would dump the content of the list into an array.
With Java 8, using an ArrayList
should be slightly faster because Collections.sort
will call List.sort
and ArrayList
has a specialised version that sorts the backing array directly, saving a copy.
So bottom line is ArrayList
is better as it gives a similar or better performance depending on the version of Java.
If you're going to be using java.util.Collections.sort(List)
then it really doesn't matter.
If the The list will get dumped into an array for purposes of sorting anyway. List
does not implement RandomAccess
, then it will be dumped to a List
(Thanks for keeping me honest Ralph. Looks like I confused the implementations of sort and shuffle. They're close enough to the same thing right?)
If you can use the Apache library, then have a look at TreeList. It addresses your problem correctly.
Only 1000 items? Why do you care?
I usually always use ArrayList unless I have specific need to do otherwise.
Have a look at the source code. I think sorting is based on arrays anyway, if I remember correctly.
If you are just sorting and not dynamically updating your sorted list, then either is fine and an array will be more memory efficient. Linked lists are really better if you want to maintain a sorted list. Inserting an object is fast into the middle of a linked list, but slow into an array.
Arrays are better if you want to find an object in the middle. With an array, you can do a binary sort and find if a member is in the list in O(logN) time. With a linked list, you need to walk the entire list which is very slow.
I guess which is better for your application depends on what you want to do with the list after it is sorted.