Created
April 24, 2014 06:20
-
-
Save gabhi/11243505 to your computer and use it in GitHub Desktop.
java custom comparator example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Comparator; | |
class Dog{ | |
int size; | |
public Dog(int s){ | |
size = s; | |
} | |
} | |
class DogSizeComparator implements Comparator<Dog>{ | |
@Override | |
public int compare(Dog o1, Dog o2) { | |
return o1.size - o2.size; | |
} | |
} | |
public class ArraySort { | |
public static void main(String[] args) { | |
Dog d1 = new Dog(2); | |
Dog d2 = new Dog(1); | |
Dog d3 = new Dog(3); | |
Dog[] dogArray = {d1, d2, d3}; | |
printDogs(dogArray); | |
Arrays.sort(dogArray, new DogSizeComparator()); | |
printDogs(dogArray); | |
} | |
public static void printDogs(Dog[] dogs){ | |
for(Dog d: dogs) | |
System.out.print(d.size + " " ); | |
System.out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment