-3

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).

4
  • 1
    Realistically these shapes should inherit from a Shape class/interface. Then you can use an array list of shapes, not objects. Commented May 9, 2021 at 15:38
  • Or of a common superclass (maybe Shape?) Commented May 9, 2021 at 15:38
  • Please don’t downvote and get my question closed.. Commented May 9, 2021 at 15:40
  • Does this answer your question? Creating instance list of different objects Commented May 9, 2021 at 18:53

1 Answer 1

0

If you can't make an interface for these classes, you can use wildcard

ArrayList<?> shapes = new ArrayList<>();
shapes.add(new WhateverYouWant());
Sign up to request clarification or add additional context in comments.

2 Comments

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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.