A Class Implements the Comparable Interface

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - A Class Implements the Comparable Interface

This is a Java example program.

[edit] Java Source Code

  • Package: example.comparator
  • File: Time.java
  1. package example.comparator;
  2.  
  3. public class Time implements Comparable {
  4.     private int hour, minute;
  5.  
  6.     public Time(int hh, int mm) {
  7. 	this.hour = hh;
  8. 	this.minute = mm;
  9.     }
  10.  
  11.     public int compareTo(Object o) {
  12. 	Time t = (Time) o;
  13. 	return hour != t.hour ? hour - t.hour : minute - t.minute;
  14.     }
  15.  
  16.     public boolean equals(Object o) {
  17. 	Time t = (Time) o;
  18. 	return hour == t.hour && minute == t.minute;
  19.     }
  20.  
  21.     public int hashCode() {
  22. 	return 60 * hour + minute;
  23.     }
  24. }

[edit] What Result You Can Get

Coming soon...

[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