java.util.Comparable Interface
java.util.Comparable interface i aşağıdaki gibidir.
1 2 3 | public interface Comparable<T> { public int compareTo(T o); } |
Karşılaştırılan objelere göre input objesi büyükse negatif integer, objeler eşit ise sıfır, input objesi küçükse pozitif integer dönülür.
Eğer elemanları Comparable interface ini implement etmeyen bir listeyi, Collections.sort(list) ile sıralamaya çalışırsanız ClassCastException i atılır.
Örnek:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | /** * * @author ugurd */ public class Node implements Comparable<Node> { public String name; public int value; public Node(int value, String name) { this.value = value; this.name = name; } public int compareTo(Node o) { if (this.value < o.value) { return -1; } else if (this.value == o.value) { return 0; } else { return 1; } } public static void main(String[] args) { Node n1 = new Node(1, "a"); Node n2 = new Node(2, "b"); Node n3 = new Node(1, "c"); System.out.println(n1.compareTo(n3)); System.out.println(n1.compareTo(n2)); System.out.println(n2.compareTo(n3)); } } |
Output:
run:
0
-1
1
BUILD SUCCESSFUL (total time: 0 seconds)