Arranging by Alphabetical Order

前端 未结 2 794
庸人自扰
庸人自扰 2021-01-24 06:20

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(\

2条回答
  •  轮回少年
    2021-01-24 06:27

    You can use the Collection class and sort the list of term you have, you need only to make the class Term comparable

    Example:

    public class Term implements Comparable {
        .....
        //  .....
        //  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 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);
    }
    

    Edit>

    if you dont want to implement comparable then modify this:

    res = maxtest.compareTo(maxtest2);
    

    because this is not valid since maxtest and maxtest2 are primitives and not objects...

    use instead

    res = Character.compare(maxtest, maxtest2);
    

    and then use the result to verify your logic and make decisions:

    if (res >1) {
                System.out.println("bigger");
    
            }else if (res<1) {
                System.out.println("smaller");
    
            }else {
                System.out.println("same");
    
            }
    

提交回复
热议问题