Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting An Array of Objects

 
Duane Eddy
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
tisham
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
The dictionary class might be helpful in comparing and sorting strings!!Just a suggestion
Cheers
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by tisham:

The dictionary class might be helpful in comparing and sorting strings!!

Would it? In which way?
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Duane Eddy
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does anyone have an example of using a comparitor?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Duane Eddy:
Does anyone have an example of using a comparitor?

Yes: http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
BTW, I found this by searching for "java comparator tutorial" at www.google.com
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic