按照字母顺序排列 [英] Arranging by Alphabetical Order

查看:190
本文介绍了按照字母顺序排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Java和我试图姓名字母顺序排列方面的ArrayList。 (A术语定义为char和一个int)(例如: {期限('Z',4),期限('C',3),期限('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) ...} )

我的code是如下:

    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是名词叫做填充类型期限

Why isn't this working? and how do I accomplish this? My arrayList is called term filled with type Term

推荐答案

您的问题与该行code的。您的类不是一个类型可比因此,在该财产或标准的compareTo()方法将比较这两个对象???

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.

您必须需要让你的类期限可比类型。并且,覆盖的方法的compareTo()根据自己的需要。

You must need to make your class Term Comparable type. and , Override the method compareTo() as per your need.

您还没有提你的类的变量或结构期限。所以,我假设你的类有这样的一种结构。

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;
        }

    }

现在您的学生成为了媲美键入。所以,你可以申请 Col​​lections.sort(收藏OBJ)自动排序你的的ArrayList&LT;条款&GT ;

Now Your Class become a comparable Type. So you may apply Collections.sort(Collection obj) which automatically sort your 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);
}

这篇关于按照字母顺序排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆