您在这行代码中遇到的问题.您的类不是可比较的类型,因此,在哪个属性或条件上compareTo()方法将比较这两个对象?
res = maxtest.compareTo(maxtest2); //Your maxtest object is not Comparable Type.
您必须使您的类Term Comparable类型.和根据您的需要重写compareTo()方法.
您没有提到Term类的变量或结构.因此,我假设您的班级有这种Structure.
public class Term implements Comparable {
private Character alpha;
private int number;
//getter and setters +Constructors as you specified
....
....
...
.....
// Now Set a criteria to sort is the Alphanumeric.
@Override
public int compareTo(Term prm_obj) {
if (prm_obj.getAlpha() > this.alpha) {
return 1;
} else if (prm_obj.getAlpha() < this.alpha) {
return -1;
} else {
return 0;
}
}
现在,您的班级成为可比较的类型.因此,您可以应用Collections.sort(Collection obj),它会自动对ArrayList< Term>进行排序.
在这里,我为此编写了一个演示.
public static void main(String... args){
List obj_listTerm = new ArrayList<>();
//add all the data you given in question
obj_listTerm .add(new Term('Z', 4));
obj_listTerm .add(new Term('Q', 2));
obj_listTerm .add(new Term('c', 3));
// print without Sorting your Term ArrayList.
System.out.println("This is the list unsorted: " + myTermList);
// Sort Using Collections.sort() Method.
Collections.sort(myTermList);
// After applying sort() you may see your Sorted ArrayList.
System.out.println("This is the list SORTED: " + myTermList);
}