Source link:
ArrayList Vs LinkedList In Java.

ArrayList Vs LinkedList In Java.
Sorting Array of String or objects
Solution with Collections.sort
If you are forced to use that List, or if your program has a structure like
- Create List
- Add some country names
- sort them once
- never change that list again
then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:
java.util.Collections.sort(listOfCountryNames, Collator.getInstance());
Solution with a TreeSet
If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().
Collection<String> countryNames =new TreeSet<String>(Collator.getInstance());countryNames.add("UK");countryNames.add("Germany");countryNames.add("Australia");// Tada... sorted.
Side note on why I prefer the TreeSet
This has some subtle, but important advantages:
- It's simply shorter. Only one line shorter, though.
- Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do.
- You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List.
- An experienced programmer looks at
TreeSetand instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.countyNames - Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.
Il allows you to pass an instance of Comparator to sort according to your needs. Note that thejavadoc of Comparator contains guidelines regarding the building of comparators.
You may define the comparator as an anonymous class if it's only locally used. Here's an example where I sort objects regarding to one of their fields which is a String :
Alternatively, you might also make your class implement the Comparable interface but this makes sense only if you can define a natural (obvious) order.
I would create an inner class implementing the Comparator interface:
Now when you want to sort your Car list by horsePower:
|
No comments:
Post a Comment