java4all@1986 java. Powered by Blogger.

Creating a Comparable object

>> Tuesday, May 24, 2011

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 = (Personobj;
    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 = (Personobj;
    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);
  }
}
           
        

0 comments:

Post a Comment

FaceBook Login

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

HTML/JAVASCRIPT

Total Pageviews

STATCOUNTER

  © Blogger template Simple n' Sweet by Ourblogtemplates.com 2009

Back to TOP