我是Java的新手,正在尝试按字母顺序排列术语的arrayList。(一个术语定义为一个字符和一个整数)(例如{Term('Z',4),Term('C',3),Term('Q',2) ...} )
{Term('Z',4),Term('C',3),Term('Q',2) ...} )
我的代码如下:
public Term nextElement() { Term max = terms.get(0); char maxtest = max.getElement(); for (int i = 1; i < terms.size(); i++){ Term tester = terms.get(i); char maxtest2 = tester.getElement(); if (maxtest2 > maxtest) { tester = max; } } return max; }
为什么这不起作用?以及我该如何完成呢?我的arrayList称为术语,填充有Term类型
您在这行代码中遇到的问题。您的课程不是ComparableSo 的类型,这两个对象compareTo()将基于哪个属性或条件方法compare?
Comparable
compareTo()
compare
res = maxtest.compareTo(maxtest2); //Your maxtest object is not Comparable Type.
您必须使您的类为TermComparable类型。和,compareTo()根据您的需要覆盖该方法。
Term
您没有提到类的变量或结构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(Collection obj)自动sort的ArrayList<Term>。
comparable
Collections.sort(Collection obj)
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); }