This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I've created a class with several string variables. I created an ArrayList of the class objects. I want to sort the list on one of the variables. I change the list to an array to sort it. When I try to sort the array I get a java.lang.ClassCastException error.
Do I need a comparator? What is a comparator and how do I use it here? [ May 31, 2002: Message edited by: Duane Eddy ]
You need a comparitor or a compareTo() method. If you have a compareTo(), you should have an equals(). If you have an equals(), you must have a hashCode(). So providing a comparitor might be simpler. However, here is a demo with CompareTo.
Originally posted by Duane Eddy: I change the list to an array to sort it.
You could use one of the Collections.sort methods instead.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joined: Jul 11, 2001
Originally posted by tisham:
The dictionary class might be helpful in comparing and sorting strings!!
Would it? In which way?
Joined: Feb 22, 2001
As suggested, there is no need to convert to an array to sort. But I would think that to do any sorting, one would need criteria for comparing the objects. Hence the need for Comparable (that is, with a compareTo()) or a Comparitor (with its compare() method). Once you provide a way to compare -- a sorting order -- you might even find you want to use a SortedSet (TreeSet) instead of an unsorted List (ArrayList) -- if Set semantics match your requirements better than List semantics. [ June 01, 2002: Message edited by: John Dale ]
Joined: May 30, 2002
Does anyone have an example of using a comparitor?
Joined: Jul 11, 2001
Originally posted by Duane Eddy: Does anyone have an example of using a comparitor?