Blank Reaver
Blank Reaver

Reputation: 225

Find the largest area of various Shape objects from an ArrayList

Ideally I do not want it to be static or void. It is the only way I could get it to work at the moment.

I have a Shape superclass. It has a method of area() which I @Override in the Rectangle class and Circle class. In my main method utilizing File IO. I am trying to make a method to iterate though my ArrayList of Shapes, to find the largest area().

I get a couple of different errors when I try different things. When I try something like, Shape largest = largest.get(0).area(); I get an error saying I cannot convert a double to a shape.

I want to be able to get an area from my arrayList, and then compare it to other areas from that ArrayList, and do a sort method to find the largest and store it and return it. Also when I try returning it wont let me because it is not static.

But I cant make my other methods static, that is not part of the design. Following is a method I have been trying with a foreach, I know it is not right, but can I use it potentially? How can I get it to store the object I create e without overwriting it each time?

If more code uploaded would be helpful please let me know.

Java

public static void shapeWithLargestArea(ArrayList<Shape> shapes) {

     for(Shape e: shapes) {
         double largest = e.area();
           if (e.area() > largest) {
               largest = e.area();
           }
            System.out.println(largest);
     } // end for each loop


} // end largest area method 

Upvotes: 0

Views: 1687

Answers (1)

Fran&#231;ois LEPORCQ
Fran&#231;ois LEPORCQ

Reputation: 552

Your code can't compile with Shape largest = largest.get(0).area(); because your area() method return a double and you try to put in a variable typed with Shape.

You can implement this

public static Shape shapeWithLargestArea(ArrayList<Shape> shapes) {
    Shape largestShape = null;
    for(Shape shape: shapes) {
        if(largestShape == null || shape.area() > largestShape.area())
            largestShape = shape;
    } 
    return largestShape;
}

But in java 8, I think you can write more elegant code with streams

write an inner comparator class in your Shape class :

private static class ShapeAreaComparator implements Comparator<Shape> {
    @Override
    public int compare(Shape s1, Shape s2) {
        return s1.area().compareTo(s2.area());
    }
}

and use it in a static method of your class like this

public static Shape shapeWithLargestArea(ArrayList<Shape> shapes) {
    return shapes.stream().max(new ShapeAreaComparator()).get();
}

but your area() method must return a Double and not a double to use the compareTo() method

Upvotes: 2

Related Questions