按字母顺序排列 [英] Arranging by Alphabetical Order
问题描述
我是 Java 新手,我正在尝试按字母顺序排列术语数组列表.(术语定义为字符和整数)(例如 {Term('Z',4),Term('C',3),Term('Q',2) ...} )代码>
I'm new to Java and I'm trying to arrange an arrayList of terms in alphabetical order. (A term is defined as a char and an int) (e.g. {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 填充类型 Term
Why isn't this working? and how do I accomplish this? My arrayList is called term filled with type Term
推荐答案
这行代码的问题.您的类不是 Comparable
的类型,因此,compareTo()
方法将compare
这两个对象在哪个属性或条件上compare
???>
Your problem with this line of Code. Your class is not a Type of Comparable
So, On which property or criteria compareTo()
method will compare
these two objects ???
res = maxtest.compareTo(maxtest2); //Your maxtest object is not Comparable Type.
您必须使您的类 Term
成为可比较类型.并且,根据您的需要覆盖方法 compareTo()
.
You must need to make your class Term
Comparable type. and , Override the method compareTo()
as per your need.
您没有提到类 Term
的变量或结构.所以,我假设你的班级有这种结构.
You have not mentioning the variable's or structure of your class Term
. So, I am assuming that your class have such kind of 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
.
Now Your Class become a comparable
Type. So you may apply Collections.sort(Collection obj)
which automatically sort
your ArrayList<Term>
.
在这里我为此编写了一个演示.
Here I write a demo for this.
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);
}
这篇关于按字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!