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
The dictionary class might be helpful in comparing and sorting strings!!
Would it? In which way?
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
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 ]
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
When people don’t understand what you are doing they call you crazy. But this tiny ad just doesn't care:
a bit of art, as a gift, the permaculture playing cards