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(\
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.
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 {
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;
}
}
Now Your Class become a comparable
Type. So you may apply Collections.sort(Collection obj)
which automatically sort
your ArrayList
.
Here I write a demo for this.
public static void main(String... args){
List 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);
}