Results 1 to 1 of 1
Thread: Creating a Comparable object
-
Creating a Comparable object
Java Code:import java.util.Arrays; import java.util.Set; import java.util.TreeSet; public class Person implements Comparable { String firstName, lastName; public Person(String f, String l) { this.firstName = f; this.lastName = l; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String toString() { return "[dept=" + firstName + ",name=" + lastName + "]"; } public int compareTo(Object obj) { Person emp = (Person) obj; int deptComp = firstName.compareTo(emp.getFirstName()); return ((deptComp == 0) ? lastName.compareTo(emp.getLastName()) : deptComp); } public boolean equals(Object obj) { if (!(obj instanceof Person)) { return false; } Person emp = (Person) obj; return firstName.equals(emp.getFirstName()) && lastName.equals(emp.getLastName()); } public static void main(String args[]) { Person emps[] = { new Person("Debbie", "Degree"), new Person("Geri", "Grade"), new Person("Ester", "Extent"), new Person("Mary", "Measure"), new Person("Anastasia", "Amount") }; Set set = new TreeSet(Arrays.asList(emps)); System.out.println(set); } }"The sole cause of man’s unhappiness is that he does not know how to stay quietly in his room." - Blaise Pascal
Similar Threads
-
Need help with creating array of type object
By riz618 in forum New To JavaReplies: 3Last Post: 01-29-2008, 06:14 AM -
Creating a File object in Servlet
By Java Tip in forum Java TipReplies: 0Last Post: 01-16-2008, 10:24 AM -
Creating Document object for XML parsing
By Java Tip in forum Java TipReplies: 0Last Post: 11-19-2007, 04:12 PM -
Creating object of Type Object class
By venkatv in forum New To JavaReplies: 3Last Post: 07-17-2007, 03:33 PM -
OutOfMemoryError while creating a new object of file with size more than 150 MB
By Jamie in forum Advanced JavaReplies: 1Last Post: 05-20-2007, 08:52 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks