25.02.2017 Views

java_tutorial

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Java<br />

obj is the object to be tested for equality. The method returns true if obj and the invoking<br />

object are both Comparator objects and use the same ordering. Otherwise, it returns false.<br />

Overriding equals( ) is unnecessary, and most simple comparators will not do so.<br />

Example<br />

import <strong>java</strong>.util.*;<br />

class Dog implements Comparator, Comparable{<br />

private String name;<br />

private int age;<br />

Dog(){<br />

}<br />

Dog(String n, int a){<br />

name = n;<br />

age = a;<br />

}<br />

public String getDogName(){<br />

}<br />

return name;<br />

public int getDogAge(){<br />

}<br />

return age;<br />

// Overriding the compareTo method<br />

public int compareTo(Dog d){<br />

return (this.name).compareTo(d.name);<br />

}<br />

}<br />

// Overriding the compare method to sort the age<br />

public int compare(Dog d, Dog d1){<br />

return d.age - d1.age;<br />

}<br />

454

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!