Making Java Objects Comparable

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Making Java Objects Comparable

This Java example program shows how to make Java Objects comparable.

[edit] Java Source Code

  • Package: example.comparator
  • File: Person.java
  1. package example.comparator;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Set;
  5. import java.util.TreeSet;
  6.  
  7. public class Person implements Comparable {
  8.     String firstName, lastName;
  9.  
  10.     public Person(String f, String l) {
  11. 	this.firstName = f;
  12. 	this.lastName = l;
  13.     }
  14.  
  15.     public String getFirstName() {
  16. 	return firstName;
  17.     }
  18.  
  19.     public String getLastName() {
  20. 	return lastName;
  21.     }
  22.  
  23.     public String toString() {
  24. 	return "[dept=" + firstName + ",name=" + lastName + "]";
  25.     }
  26.  
  27.     public int compareTo(Object obj) {
  28. 	Person emp = (Person) obj;
  29. 	int deptComp = firstName.compareTo(emp.getFirstName());
  30.  
  31. 	return ((deptComp == 0) ? lastName.compareTo(emp.getLastName()) : deptComp);
  32.     }
  33.  
  34.     public boolean equals(Object obj) {
  35. 	if (!(obj instanceof Person)) {
  36. 	    return false;
  37. 	}
  38. 	Person emp = (Person) obj;
  39. 	return firstName.equals(emp.getFirstName()) && lastName.equals(emp.getLastName());
  40.     }
  41.  
  42.     public static void main(String args[]) {
  43. 	Person emps[] =
  44. 		{ new Person("Debbie", "Degree"), new Person("Geri", "Grade"), new Person("Ester", "Extent"),
  45. 			new Person("Mary", "Measure"), new Person("Anastasia", "Amount") };
  46. 	Set set = new TreeSet(Arrays.asList(emps));
  47. 	System.out.println(set);
  48.     }
  49. }

[edit] What Result You Can Get

Run the program, you will get:

[[dept=Anastasia,name=Amount], [dept=Debbie,name=Degree], [dept=Ester,name=Extent], [dept=Geri,name=Grade], [dept=Mary,name=Measure]]

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools