Created
August 16, 2012 18:09
-
-
Save hamaluik/3372229 to your computer and use it in GitHub Desktop.
Sorting objects in Java
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
class Derp { | |
// hold the rank of each derp here | |
int rank; | |
} | |
// now, we must make a comparator class which knows how to sort our Derp class: | |
class DerpComp implements Comparator<Derp> { | |
public int compare(Derp a, Derp b) { | |
// return -1 if a < b | |
if(a.rank < b.rank) | |
return -1; | |
// return 1 if a > b | |
else if(a.rank > b.rank) | |
return 1; | |
// return 0 if a = b | |
else | |
return 0; | |
} | |
} | |
// now we can sort our derps! | |
Comparator<Derp> derpComp = new DerpComp(); | |
Arrays.sort(derps, derpComp); | |
// and done! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment