Java compareTo作用

Java compareTo作用是对一个类中的属性以一定的方式进行组织,写好了可以让数据更有序.

package ACM常用; import java.util.*; class Node implements Comparable { public int val; public Node(int v) { this.val = v; } public int compareTo(Object obj) { if (obj instanceof Node) { Node oo = (Node) obj; if (this.val < oo.val) return -1; if (this.val > oo.val) return 1; } return 0; } } public class Main { public static void main(String args[]) throws Exception { int i; Scanner cin = new Scanner(System.in); Node a[] = new Node[4]; for (i = 0; i < 4; i++) a[i] = new Node(i + 1); Arrays.sort(a); for (i = 0; i < 4; i++) System.out.print(a[i].val + ((i == 3) ? "/n" : " ")); } } /////////////////////// Integer中compareTo实现 public int compareTo(Integer anotherInteger) { int thisVal = this.value; int anotherVal = anotherInteger.value; return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1)); } String类中compareTo实现 public int compareTo(String anotherString) { int len1 = count; int len2 = anotherString.count; int n = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int i = offset; int j = anotherString.offset; if (i == j) { //如果两个字符串长度相等 int k = i; int lim = n + i; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } } else { //如果不相等,则只比较n次(n 为较短的字符串的长度) while (n-- != 0) { char c1 = v1[i++]; char c2 = v2[j++]; if (c1 != c2) { return c1 - c2; } } } //如果它们没有不同的索引位置,则较短字符串在字典顺序上位于较长字符串的前面。 //这种情况下,compareTo 返回这两个字符串长度的不同 return len1 - len2; }   

你可能感兴趣的:(java,c,exception,String,Integer,Class)