I'm trying to sort a Vector with the static method sort() in Collections. The problem is that I want to sort it according to the Swedish language. It's possible to send an object of Collator with the sort-method (set to Locale swedish), but it doesn't seem to work. In my vector I have put objects of a class of persons (home-made class) and I want to sort it by last name, then by first name. Does my person's class need a specific method? It already have equals(),compare(Object o,Object o2) and hashCode(). ------------------
If it already has a compare method then that establishes the Default ordering that is use for the sorting of your Objects in a Vector or Array. If you want a different Order you will need to create a class that implements the Comparator Interface. Then when you call the sort method in Arrays, you pass the Collection of your Objects and the Comparator Object you created. Here's an example of sorting arrays based on different sorts that I like to use to show this.
Results from running EmployeeSortTest: As Entered A 23 45000 B 29 66000 F 25 54000 B 21 30000 C 22 44000 Natural Sort Order A 23 45000 B 29 66000 B 21 30000 C 22 44000 F 25 54000 Name Age Sort Order A 23 45000 B 21 30000 B 29 66000 C 22 44000 F 25 54000 Salary Sort Order B 21 30000 C 22 44000 A 23 45000 F 25 54000 B 29 66000
Thanks for a quick response! I think I beginning to get the hang of it, but how do I get it to sort according to a specific language. I have tried the method Collections.sort(arr,Collator.getInstance(new Locale("sv","SE"))). I have to make sure it sort by swedish since our language have som special letters (�,�,�) ------------------
Niklas, You may follow the brillant example given by Carl, by designing your own FullNameComparator inner class in the compare method, and by using the Collator class in the compare method. Assuming you only want to sort your persons this way, you could code it by default in the Person's Comparable interface as follows - reinterpreting Carl's example Person.java
Notice that you might set your default locale at the start of your application or in your environment, rather than hard-coding it in your classes. Regards, Beno�t