Created
June 5, 2017 20:43
-
-
Save Mladia/57ab78effc9358381ae1b52dab62ec19 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Test.java | |
import java.util.Comparator; | |
import java.util.PriorityQueue; | |
public class Test | |
{ | |
public static void main(String[] args) | |
{ | |
Comparator<String> comparator = new StringLengthComparator() { | |
@Override | |
public int compare(String x, String y) | |
{ | |
// Assume neither string is null. Real code should | |
// probably be more robust | |
// You could also just return x.length() - y.length(), | |
// which would be more efficient. | |
if (x.length() < y.length()) | |
{ | |
return -1; | |
} | |
if (x.length() > y.length()) | |
{ | |
return 1; | |
} | |
return 0; | |
} | |
} | |
PriorityQueue<String> queue = | |
new PriorityQueue<String>(10, comparator); | |
queue.add("short"); | |
queue.add("very long indeed"); | |
queue.add("medium"); | |
while (queue.size() != 0) | |
{ | |
System.out.println(queue.remove()); | |
} | |
} | |
} | |
// StringLengthComparator.java | |
import java.util.Comparator; | |
public class StringLengthComparator implements Comparator<String> | |
{ | |
@Override | |
public int compare(String x, String y) | |
{ | |
// Assume neither string is null. Real code should | |
// probably be more robust | |
// You could also just return x.length() - y.length(), | |
// which would be more efficient. | |
if (x.length() < y.length()) | |
{ | |
return -1; | |
} | |
if (x.length() > y.length()) | |
{ | |
return 1; | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment