Results 1 to 2 of 2
Thread: how compareTo Method works
- 06-22-2008, 06:07 AM #1
Member
- Join Date
- May 2008
- Posts
- 31
- Rep Power
- 0
how compareTo Method works
Hi Guys
I have understood until how to reach upto "compreTo" method. But i didn't understand how this "compareTo" method sort the array. Can please some one explain on this. Mainly my confusion is , if you see below code.
Collections.sort(names);
i know the above statement points to below method.
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp :
firstName.compareTo(n.firstName));
}
My Question is
compreTo(Name n) getting Name Object so that we got n.lastName value.
How it is sorting? a bit confusion.
the above method from this class
import java.util.*;
public class Name implements Comparable<Name> {
private final String firstName, lastName;
public Name(String firstName, String lastName) {
if (firstName == null || lastName == null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name)o;
return n.firstName.equals(firstName) &&
n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
public String toString() {
return firstName + " " + lastName;
}
public int compareTo(Name n) {
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp != 0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}
- 06-22-2008, 07:40 PM #2
Further problem statement needed.
Java Code:// How it is sorting? a bit confusion. // You are telling collections how to // do the sorting and searching. // CompareTo(Name n) uses String Object // So to compare by n.lastName value: CompareToMethodWorks{ public Name(String firstName, String lastName) { if (firstName == null || lastName == null) throw new NullPointerException(); this.firstName = firstName; this.lastName = lastName; } public int compareTo(Name n) { if( n != null ) && n instanceof String) { String s = (String) n; int result = n.compareTo(s); // ..... deletions awaiting further problem definition. } }
Similar Threads
-
compareTo()
By Tsiliadoros in forum Advanced JavaReplies: 5Last Post: 10-03-2008, 01:18 PM -
Second level caching in Hibernate: when it works?
By leonus in forum JDBCReplies: 0Last Post: 06-04-2008, 01:24 PM -
Project works in debugger, not after compiling
By Fleur in forum New To JavaReplies: 11Last Post: 05-29-2008, 09:04 AM -
How DataSource Concept works in Spring Framework
By Java Tip in forum Java TipReplies: 0Last Post: 04-01-2008, 10:40 AM -
How DataSource Concept works in Spring Framework
By JavaBean in forum Java TipReplies: 0Last Post: 09-28-2007, 12:58 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks