| Forums.Sureshkumar.net : A Perfect Place to Share Knowledge Blogs Games Magazines |
|
|
#1 (permalink) |
|
Senior Member
Join Date: Oct 2006
Location: Mayiladurai (TN)
Posts: 233
Thanks: 8 Thanked 7 Times in 5 Posts Thanks: 8
Thanked 7 Times in 5 Posts
Rep Power: 5
|
Query on comapareTo method
Following is the program to sort the employees on the Name basis
import java.util.*; class EmployeeSortTest { public static void main ( String[] tam ) { // Array of Employees Employee[] a = new Employee[3]; a[0] = new Employee("Tam",350000); a[1] = new Employee("Dravid",500000); a[2] = new Employee("Sachin",700000); // Sorting the Employees with name basis using Arrays utility class Arrays.sort(a); for( Employee x : a) System.out.println(" Name = " + x.getName() + "Salary = " + x.getSalary()); } } class Employee implements Comparable { public Employee(String n, double s ) { name = n; salary = s; } public int compareTo(Employee other) { return name.compareTo(other.name); } public String getName() { return name; } public double getSalary() { return salary; } private double salary; private String name; } My problem is I also want to sort the Employees on the Salary basis without modifying this existing code. i.e to have an another version of compareTo() method in this class that implements Comparable interface which sort on salary basis public int compareTo(Employee other) { if ( salary > other.salary) return 1; if ( salary < other.salary) retrurn -1; return 0; } But compiler reports that compareTo() is already defined in Employee Pls give solution to this |
|
|
|
|
|
#2 (permalink) |
|
Moderator
Join Date: Apr 2006
Location: India
Posts: 636
Thanks: 57 Thanked 78 Times in 63 Posts Thanks: 57
Thanked 78 Times in 63 Posts
Rep Power: 17
|
Re: Query on comapareTo method
Here you are breaking the rule of overriding, since how to override the method with same signature in the same class itself, or else what u have to do is create a subclass and in the subclass try to override the compareTo Method, then it will work
I hope im clear, if u didnot understand feel free to ask me Let me know your questions Thank You
__________________
M0h@n |
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | Rate This Thread |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| java notes | naga | JAVA Technologies | 5 | 22-09-06 10:30 PM |
| ejb | bujjimadhu | JAVA Technologies | 4 | 10-09-06 10:15 PM |
| java JSP | naga | JAVA Technologies | 4 | 21-08-06 05:03 PM |
| JAVA collection | naga | JAVA Technologies | 0 | 21-02-06 06:01 AM |
| JAVA PART3 | naga | JAVA Technologies | 0 | 18-02-06 07:48 AM |