1

I want to use the Comparator object of the Collections framework to sort out an ArrayList by an specific attribute.

I have an ArrayList called measureEviArray this array contains objects type MeasureEvi.

The class MeasureEvi has an attribute called mCoordenate which corresponds to a PointF data type.

public class MeasureEvi {

private int mIndex;                             //  
private int mOrderIndex;
private int eIndex;                             // 
private TextView mTag;                          // 
private PointF mCoordenate; 
}

What I want is to sort out that array depending on the coordenates given to each object in X (mCoordenate.x)

Is it possible to use Collections for this and get an Array Ordenate from the minor to the greatest in X axis?

I was trying to implement this way:

 Collections.sort(measureEviArray, new Comparator<MeasureEvi>() {
        @Override
        public int compare(MeasureEvi measureEvi, MeasureEvi t1) {
            return measureEvi.getmCoordenate().x.compareTo(t1.getmCoordenate().x);
        }
    });

but compareTo is not an Option, cannot resolve method.

1
  • Is x an int? If so, use Integer.compare(x1, x2). Commented Apr 24, 2017 at 18:14

1 Answer 1

2

Since x from PointF is a float, use Float.compare(float f1, float f2):

return Float.compare(measureEvi.getmCoordenate().x, t1.getmCoordenate().x);
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know if I use this to compare Integer, would it work in android < 4.4, I am getting the following observation: add @Requires API 4.4 KITKAT
@Juanca If you look at the documentation for Integer.compare(int x, int y), you'll see "added in API level 19", and following that link shows that to be Android 4.4, so no.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.