我是Java的新手,我正在尝试按字母顺序排列术语的数组列表。 (术语定义为char和int)(例如{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
答案 0 :(得分:2)
您对此行代码的问题。您的类不是logstash
类型,那么,{
"message" => "...",
"host" => "10.10.10.20",
"@version" => "1",
"@timestamp" => "2016-04-12T02:28:18.233Z",
"type" => "snmptrap",
"1_3_6_1_2_1_1_3_0" => "21 days, 17:08:57.94",
"1_3_6_1_6_3_1_1_4_1_0" => "specific::userdefined",
}
方法将Comparable
这两个对象的compareTo()
方法
compare
您必须使您的课程 res = maxtest.compareTo(maxtest2); //Your maxtest object is not Comparable Type.
成为可比类型。并根据需要覆盖方法Term
。
您没有提及班级compareTo()
的变量或结构。所以,我假设你的班级有这种结构。
Term
现在您的班级成为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>
答案 1 :(得分:0)
您可以使用Collection类并对您拥有的术语列表进行排序,您只需要使术语可比较
public class Term implements Comparable<Term> {
.....
// .....
// criteria to sort is the char
@Override
public int compareTo(Term o) {
if (o.getLetter()> this.letter) {
return 1;
} else if (o.getLetter() < this.letter) {
return -1;
} else {
return 0;
}
}
public static void main(String[] args) {
// test
List<Term> myTermList = new ArrayList<>();
myTermList.add(new Term('Z', 4));
myTermList.add(new Term('Q', 2));
myTermList.add(new Term('c', 3));
// check how the look like
System.out.println("This is the list unsorted: " + myTermList);
// now sort them
Collections.sort(myTermList);
// check how the look like
System.out.println("This is the list SORTED: " + myTermList);
}
如果你不想实现可比性,那么修改一下:
res = maxtest.compareTo(maxtest2);
因为这是无效的,因为maxtest和maxtest2是基元而不是对象......
改为使用
res = Character.compare(maxtest, maxtest2);
然后使用结果验证您的逻辑并做出决定:
if (res >1) {
System.out.println("bigger");
}else if (res<1) {
System.out.println("smaller");
}else {
System.out.println("same");
}