Connecting Tech Pros Worldwide Forums | Help | Site Map

Comparator

mia023's Avatar
Member
 
Join Date: May 2007
Posts: 89
#1: Dec 27 '07
How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them

BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#2: Dec 27 '07

re: Comparator


Quote:

Originally Posted by mia023

How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them

If there is a natural ordering you can have the class implement Comparable:

Comparable API

And in general, you can define a Comparator:

Comparator API

Despite their similar names, don't confuse them. For example, String is Comparable, because there is a natural ordering on Strings; the String class also provides the Comparator CASE_INISENSITIVE_ORDER to allow you to compare pairs of string, ignoring their case.

CASE_INSENSITIVE_ORDER API

Also, check out Sun's tutorial on this:

Collection Algorithms
mia023's Avatar
Member
 
Join Date: May 2007
Posts: 89
#3: Dec 28 '07

re: Comparator


How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
If I want to use an array to solve this problem How can I do that??
RedSon's Avatar
Site Moderator
 
Join Date: Jan 2007
Location: America
Posts: 3,393
#4: Dec 28 '07

re: Comparator


Quote:

Originally Posted by mia023

How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
If I want to use an array to solve this problem How can I do that??

IIRC, comparators just compare two items and return a negative number, a positive number or zero if they are equivalent.

Since strings have a built in comparator all you need to do is implement the comparator in your student class and use the last name string data and compare it and pass up the result.
BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#5: Dec 28 '07

re: Comparator


Quote:

Originally Posted by mia023

How do we compare objects in java? for example if we have a student class and we want to compare their last names and sort them
If I want to use an array to solve this problem How can I do that??

You posted this question yesterday.

yesterday's post
RedSon's Avatar
Site Moderator
 
Join Date: Jan 2007
Location: America
Posts: 3,393
#6: Dec 28 '07

re: Comparator


mia023,

Do not double post your questions. Doing so again will get you severe consequences.
BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#7: Dec 28 '07

re: Comparator


Quote:

Originally Posted by mia023

If I want to use an array to solve this problem How can I do that??

One way is to use the utility class java.util.Arrays:

java.util.Arrays
Reply