您在这行代码中遇到的问题。您的课程不是
ComparableSo 的类型,这两个对象
compareTo()将基于哪个属性或条件方法
compare?
res = maxtest.compareTo(maxtest2); //Your maxtest object is not Comparable Type.
您必须使您的类为
TermComparable类型。和,
compareTo()根据您的需要覆盖该方法。
您没有提到类的变量或结构
Term。因此,我假设您的班级具有这种Structure。
public class Term implements Comparable<Term> { 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; } }现在,您的班级成为
comparable类型。所以,你可以申请
Collections.sort(Collectionobj)自动
sort的
ArrayList<Term>。
在这里,我为此编写了一个演示。
public static void main(String... args){ List<Term> 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);}


