Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to implement custom methods of an ArrayList in Java?

Tags:

java

arraylist

Lets suppose that I have an ArrayList defined as follows:

ArrayList<Employee> listWithItems=new ArrayList();

I was wondering if there is a way so that I can create a custom method and call it from the ArrayList created. I mean, for example if I create a method for computing the taxes I want to call it like this:

listWithItems.computeTaxes();

Is there a way to extend the ArrayList in Java to implement custom user methods? I mean if there is like an ArrayList interface that I could use it for those purposes.

Thanks

like image 493
Little Avatar asked May 30 '26 10:05

Little


1 Answers

Yes, you could extend (subclass) ArrayList.

But that's not a good idea. You should define your own class/interface for your business object. It's all about separation of concerns and having every class do exactly one thing. A generic container (such as ArrayList) should not be dealing with taxes.

You could wrap the ArrayList into your own class, or just have a method that takes the list as a parameter.

taxCalculation.computeTaxes(listWithItems);
like image 96
Thilo Avatar answered May 31 '26 23:05

Thilo



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!