I have multiple objects set up, all implementing the same class. All of these objects have a common method, "getRatio". I want to order these objects in ascending numerical order with respect to the values of the "getRatio" method, and also have the objects call their toString methods in order. I've attempted to apply this idea, but I was only to order just the numbers themselves.
List shapeList = new ArrayList();
shapeList.add(rectangle);
shapeList.add(triangle_right);
shapeList.add(isosceles);
shapeList.add(triangle);
shapeList.add(triangle2);
shapeList.add(triangle3);
Collections.sort(shapeList);
for (Shape shape : shapeList) {
System.out.println(shape.toString());
}
no suitable method found for add(RightTriangle) shapeList.add(triangle_right);
error: cannot find symbol Comparable.sort(shapeList);
Expanding on the other answers, you could define your Comparator
and sort your array as follows:
Arrays.sort(myArray, new Comparator<MyClass>() {
@Override
public int compare(MyClass c1, MyClass c2) {
return (new Double(c1.getRatio())).compareTo(c2.getRatio());
}
});
If you plan sorting multiple arrays like this, it would be wise to make MyClass
implement the Comparable
interface.
EDIT: To sort List
s (such as ArrayList
s) you can use a similar concept, but with Collections.sort
:
Collections.sort(shapeList, new Comparator<MyClass>() {
@Override
public int compare(MyClass c1, MyClass c2) {
return (new Double(c1.getRatio())).compareTo(c2.getRatio());
}
});
Relevant documentation: