Proper Java Design for a Class with a Common Collection

Say I got classes A, B, C such that B extends A and C also extends A

Now I have 2 different classes, let's give them MyClassB and MyClassC with a member ArrayList<B> and ArrayList<C> respectfully.

Since many of the actions in MyClassB and MyClassC same and are performed only for another type of ArrayList, I wanted to create a new abstract class MyClassA that will implement the same actions on ArrayList<A> for both classes, since A is the common part, the action of which the same way.

Therefore, I tried to create a method in the new MyClassA class, which receives the list as an argument and must take an action in this list. However, I cannot pass an ArrayList<B> method in which it expects an ArrayList<A> .

So what can I do to keep the same actions in a different class and not repeat the code in two different classes?

+6
source share
3 answers
 class MyClassA<T extends A> { ArrayList<T> list; public MyClassA(ArrayList<T> list) { this.list = list; ... class MyClassB extends MyClassA<B> { MyClassB(ArrayList<B> list) { super(list); 
+3
source

Try using generics:

 public class MyClassA<T extends A> { public void doSomething(ArrayList<T> list) { // do something } } 

Now MyClassB and MyClassC can inherit it, and you can work with the list normally.

+1
source

I see two options: adding a general to the base class or working with a wildcard:

 public final class HolderB extends BaseBase<B>{ @Override public void abstractAlgo(List<B> elements) { //uses the generic from the base class //add Bs elements.add(new B()); //get Bs System.out.println(elements.get(0)); } @Override public void abstractAlgoWithWildcard(List<? extends Base> elements) { //uses the base class directly //add not possible Bs elements.add(new B()); //get Bs System.out.println(elements.get(0)); } 

}

When using a wildcard solution, it is impossible to add new elements to the list, only read operations are allowed.

0
source

Source: https://habr.com/ru/post/987864/


All Articles