How to store different types of objects in ArrayList

前端 未结 5 2030
暗喜
暗喜 2021-01-25 22:20

I need to store different objects in the ArrayList. Objects are similar in nature but different and have different methods.

Circle c = new Circle();  
Cube s =          


        
5条回答
  •  不思量自难忘°
    2021-01-25 23:23

    You can just create an ArrayList. That's a list that can store anything. It's not very useful to work with, because taking things out basically forces you to check their type in order to call any methods. For that reason you should almost always avoid doing this.

    Objects in collections usually have something in common - if they don't, you should rethink why you're throwing them into the same collection. In your case, they're all shapes. So instead, consider adding a shared interface such as Shape which combines the common functionality.

    I'm simplifying slightly because you have the concept of both 2D and 3D shapes, but here's the gist:

    interface Shape
    {
        double area();
        double perimeter();
    }
    
    class Circle implements Shape
    {
        // ...
    
        public double area()
        {
            return radius * radius * Math.PI;
        }
    
        public double perimeter()
        {
            return 2 * Math.PI * radius;
        }
    }
    
    class Square implements Shape
    {
         //...
    }
    

    And then creating a list of Shapes:

    List shapes = Arrays.asList(new Circle(3), new Square(4), ...);
    

    提交回复
    热议问题