How do i create an arraylist of many DIFFERENT OBJECTS and add their references. So like shape.add(new Rectangle(3, 2)); and like shape.add(new RightTriangle(2, 4).
Asked
Active
Viewed 56 times
-3
-
1Realistically these shapes should inherit from a `Shape` class/interface. Then you can use an array list of shapes, not objects. – Henry Twist May 09 '21 at 15:38
-
Or of a common superclass (maybe `Shape`?) – geocodezip May 09 '21 at 15:38
-
Please don’t downvote and get my question closed.. – Mike May 09 '21 at 15:40
-
Does this answer your question? [Creating instance list of different objects](https://stackoverflow.com/questions/11073539/creating-instance-list-of-different-objects) – Henry Twist May 09 '21 at 18:53
1 Answers
0
If you can't make an interface for these classes, you can use wildcard
ArrayList<?> shapes = new ArrayList<>();
shapes.add(new WhateverYouWant());

Toshimichi
- 46
- 1
- 7
-
So with that I can put anything I want meaning different objects like the shapes for example and it not throw an error at me – Mike May 09 '21 at 16:10
-
Yes but there's not much point in this approach, when you retrieve them you won't be able to call any relevant methods etc. So they might as well not be in an array in the first place. – Henry Twist May 09 '21 at 18:20