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
Comparatorand sort your array as follows:If you plan sorting multiple arrays like this, it would be wise to make
MyClassimplement theComparableinterface.EDIT: To sort
Lists (such asArrayLists) you can use a similar concept, but withCollections.sort:Relevant documentation:
ComparatorComparableArrays.sortCollections.sort