Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have define ArrayLists and Other Data Structures that extend interfaces? [duplicate]

I have many classes that implement an interface. Can I have Stacks, Queues and ArrayLists defined like this?

ArrayList<Class<? extends BaseClass>> 

to store objects ? In my scenario each object will be from a different class in the Stack, or ArrayList? What are the pros and cons of such an implementation? I am new to Java and hence this question. Any alternate recommendation to this?

like image 644
Wanderer Avatar asked Feb 22 '26 21:02

Wanderer


2 Answers

Yes, you can.

The pros are that you can store various types of objects and be assured they implement the same contract and therefore can treat them polymorphically. You wouldn't be able to store them otherwise in the single structure without using Object; assuming no other commonality exists.

The cons are that you won't know, without additional checks, their type and therefore are limited to the functionality provided by that interface. You'd then me stuck doing the check for the instance type followed by a cast in order to use the uncommon functionality.

like image 190
ChiefTwoPencils Avatar answered Feb 25 '26 10:02

ChiefTwoPencils


I have many classes that implement an interface

If BaseClass is that interface and you wish to store any sub type of BaseClass in ArrayList or Stack, declaration ArrayList<Class<? extends BaseClass>> is wrong for that purpose. It would simply be like,

List<BaseClass> arrList = new ArrayList<BaseClass>();

Can I have Stacks , Queues and ArrayLists defined like this?

Yes, you can define ArrayList or Stack on base type interface and put in Objects of concrete sub classes.

In my scenario each object will be from a different class in the Stack, or ArrayList?

Yes, if you have inserted so. You are allowed to insert any sub type of BaseClass in that ArrayList so if you have put such elements , those will be there.

What are the pros and cons of such an implementation?

These would be same as already listed in ChiefTwoPencils's answer - that you have liberty to store various types of Objects in one List but when you retrieve objects from list to work on, you might have to check their type etc ( if interested in some that sub type's specific behavior ).

Hope it helps !!

like image 28
Sabir Khan Avatar answered Feb 25 '26 09:02

Sabir Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!