• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

CompareTo Method for sorting

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can someone explain me how the CompareTo method works for sorting.What i am doing is passing a person array in Arrays.sort(Object[]) method.Here is my compareTo method..

public int compareTo(Object o) throws ClassCastException
{

//System.out.println("inside compare to method");
Person p = (Person)o;
if (!(o instanceof Person))
{
throw new ClassCastException("A Person object expected.");
}
int value = lastName.compareTo(p.lastName);

System.out.println(lastName +"+"+p.lastName);

if (value == 0)
{
value = firstName.compareTo(p.firstName);
}
System.out.println(value);

return value;
}


What i can understand from execution is ,its sorting the last names of the person.I tried printing the values it gets in the method ,but not able to understand.I feel Arrays.sort automatically calls this compareTo method.My question is how the value variable gets its value?I got some positive as well as negative value for value attribute ,then how that value is used to sort the last names?Kindly reply
 
best scout
Posts: 1294
Scala IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Umadas,

your compareTo() method in this code example first uses the compareTo() method for the lastNames and if this is equal it also comparse the firstNames. So effectively your persons are sorted by lastName and then by firstName. This is possible because lastName and firstName will most probably be built-in types (String?) for which there's already a reasonable implementation of compareTo()! So "lastName.compareTo(p.lastName);" will probably call the compareTo() method of class String!

And you're right, Arrays.sort() assumes that the objects given to it implement the Comparable interface and therefor automatically uses the compareTo() method of the objects in the array.

Marco
[ June 02, 2008: Message edited by: Marco Ehrentreich ]
 
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

By implementing the comparable interface, overriding the compareTo(Object) method we are embedding some kind of knowledge inside the object... and by knowledge I mean the way to compare with another object of the same kind... So now one Person object now knows the way to compare with another Person object... And Arrays.sort(Object[]) uses this knowledge to compare two objects of the passed array and continues it this way to sort the whole of the array...

[And the compareTo() knowledge is not just for the Arrays.sort() method to use, but also when you want to create a TreeSet()... for a TreeSet has to be sorted...]

String has the compareTo method and we're directly using that method in this code... and I guess String comparison works like as in C...

for eg:
comparing "vishwa" with "vishnu" would mean,
'v'-'v'=0 goto next character,
'i'-'i'=0
's'-'s'=0
'h'-'h'=0
'w'-'n'=some positive value and so vishwa > vishnu...

return thatValue;

if it was
'n'-'w' it would be a negative value




Hope that helps,
Vishwa
 
Ajay Singh
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks marco and vishwanath for the reply.Ok so based on the above the values are negative and positive,suppose my names are set as

1)Rahul Khanna
2)Arun Verma
3)Ajay Malhotra
4)Ajay Thakur

I get the following output for system.out.println in the compareTo method

Khanna+Verma //System.out.println(lastName+"+"+p.lastName);
-11 //this is the value variable(K<V ,so -)

Verma+Malhotra
9

Khanna+Malhotra
-2

Verma+Thakur
2

Malhotra+Thakur
-7

i got how the values are displayed based on whethere its greater or less than the passed object,but still there is one doubt as how the last names are compared since there doesn't seem to be any specific order of comparison.For example Khanna is compared with Verma and Malhotra but not with Thakur,Is there anything which i am missing here?
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Umadas Ravindran:

1)Rahul Khanna
2)Arun Verma
3)Ajay Malhotra
4)Ajay Thakur

...For example Khanna is compared with Verma and Malhotra but not with Thakur,Is there anything which i am missing here?



From what I know it goes like this,

Add Khanna (empty so nothing to compare it to)
Add Verma (compare with Khanna, add after it)
Add Malhotra (compare with Verma, goes before, compare with Khanna, goes after).
Add Thakur (compare with Verma, goes before, compare with Malhotra, goes after). There is no point to compare with Khanna here as its after Malhotra and Malhotra is after Khanna anyway!

As an experiment, if you added the name "Zack", as soon as it compared it with Verma it should not compare with any others as there is nothing after Verma in your list.

In the same way if you added "Lisa", as soon as it compared with Khanna, and Malhotra, it would find it went in between and not bother comparing with rest of Strings.
 
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey Umadas,

Could you please write the entire program,and not just the overriden menthod of CompareTo().
I am having a little trouble understanding the question as well as the answer.

Thanks.
 
Ajay Singh
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the code with which i am experimenting.The output comes as expected

Khanna, Rahul
Malhotra, Ajay
Thakur, Ajay
Verma, Arun


One point to note is that if i set "103","48","65","75" in the lastname variable instead of the khanna,malhotra etc, then the output comes as

103, Rahul
48, Arun
65, Ajay
75, Ajay

i know it takes as 1<4/6/7.but the output is wrong,how to remove this discrepancy.



Code:-

package com.example;

import java.util.Arrays;
import java.util.ArrayList;
class Person implements Comparable
{
private String firstName;
private String lastName;


public String getFirstName()
{
return firstName;
}

public void setFirstName(String firstName)
{
this.firstName = firstName;
}

public String getLastName()
{
return lastName;
}

public void setLastName(String lastName)
{
this. lastName = lastName;
}



public int compareTo(Object o) throws ClassCastException
{

Person p = (Person)o;
if (!(o instanceof Person))
{
throw new ClassCastException("A Person object expected.");
}
int value = lastName.compareTo(p.lastName);

if (value == 0)
{
value = firstName.compareTo(p.firstName);
}

return value;
}
}


public class Testing
{

public static void main(String[] args)
{
Person[] persons = new Person[4];
persons[0] = new Person();
persons[0].setFirstName("Rahul");
persons[0].setLastName("Khanna");


persons[1] = new Person();
persons[1].setFirstName("Arun");
persons[1].setLastName("Verma");


persons[2] = new Person();
persons[2].setFirstName("Ajay");
persons[2].setLastName("Malhotra");


persons[3] = new Person();
persons[3].setFirstName("Ajay");
persons[3].setLastName("Thakur");



Arrays.sort(persons);

System.out.println();
System.out.println("Sorted by lastname........\n");

for (int i=0; i<4; i++)
{
Person person = persons[i];
String x = person.getLastName();
String y = person.getFirstName();

System.out.println(x + ", " + y );
}
}
}
 
reply
    Bookmark Topic Watch Topic
  • New Topic