compare integer and int java code example
Example 1: java integer compareto
public class IntegerCompareToExample {
public static void main(String[] args) {
Integer x = new Integer("90");
Integer y= new Integer("58");
int retResult = x.compareTo(y);
if(retResult > 0) {
System.out.println("x is greater than y");
} else if(retResult< 0) {
System.out.println("x is less than y");
} else {
System.out.println("x is equal to y");
}
}
}
Example 2: compare string integer java
private int newCompareTo(String comp1, String comp2) {
if (comp1.length() == 0) {
if (comp2.length() == 0) {
return 0;
}
return -1;
} else if (comp2.length() == 0) {
return 1;
}
if (TextUtils.isDigitsOnly(comp1)) {
int val1 = Integer.parseInt(comp1);
if (TextUtils.isDigitsOnly(comp2)) {
int val2 = Integer.parseInt(comp2);
return Integer.compare(val1, val2);
} else {
return comp1.compareTo(comp2);
}
} else {
int minVal = Math.min(comp1.length(), comp2.length()), sameCount = 0;
for (int i = 0;i < minVal;i++) {
char leftVal = comp1.charAt(i), rightVal = comp2.charAt(i);
if (leftVal == rightVal) {
sameCount++;
} else {
break;
}
}
if (sameCount == 0) {
return comp1.compareTo(comp2);
} else {
String newStr1 = comp1.substring(sameCount), newStr2 = comp2.substring(sameCount);
if (TextUtils.isDigitsOnly(newStr1) && TextUtils.isDigitsOnly(newStr2)) {
return Integer.compare(Integer.parseInt(newStr1), Integer.parseInt(newStr2));
} else {
return comp1.compareTo(comp2);
}
}
}
}