Reputation: 2106
Could someone please help me out with the following problem in java. I have a simple class defined as below:
public class Expr {
public long total_apparitions;
public String expression=new String();
public Expr(long total,String expr){
this.total_apparitions=total;
this.expression=expr;
}
public void increment(long aparitions){
total_apparitions+=aparitions;
}
}
I want to sort an array of Expr
objects by the total_apparitions
field, using the Arrays.sort
built-in function. How do I specify to the Arrays.sort
function the comparison factor? Thanks a lot.
Upvotes: 0
Views: 176
Reputation: 2368
Make Expr
implement java.lang.Comparable
Edit - Should have provided an example (others already did). Here's a full sample using generics.
public class Expr implements Comparable<Expr>
{
public long total_apparitions;
public String expression = new String();
public Expr(long total, String expr)
{
this.total_apparitions = total;
this.expression = expr;
}
public void increment(long aparitions)
{
total_apparitions += aparitions;
}
public int compareTo(Expr o)
{
if (total_apparitions > o.total_apparitions)
{
return 1;
}
else if (total_apparitions < o.total_apparitions)
{
return -1;
}
else
{
return 0;
}
}
}
Upvotes: 4
Reputation: 43169
As an alternative to implementing Comparable
, you can pass a Comparator
instance to the Arrays.sort()
method. The advantage of doing it this way is that it allows you to have different concepts of sorting an array of objects of this type (say you might want to sort by the name later, in which case you just need a different implementation of the comparator).
For example:
public class ByApparationsComparator implements Comparator<Expr> {
public int compare(Expr first, Expr second) {
if (first.total_apparitions > second.total_apparitions) {
return 1;
} else if (first.total_apparitions < second.total_apparitions) {
return -1;
} else {
return 0;
}
}
}
Then you can say:
Arrays.sort(exprArray, new ByApparationsComparator());
Upvotes: 3
Reputation: 12613
As @Jason Braucht said, implement Comparable
like this:
public class Expr implements Comparable {
...
public int compareTo(Object o) {
if(this.total_apparitions > ((Expr) o).total_apparitions)
return 1;
else if(this.total_apparitions < ((Expr) o).total_apparitions)
return -1;
return 0;
}
}
Upvotes: 5