LonelyBishop :
I have class "A" that has two arrayLists of objects of two classes "BC" and "BD". BC and BD inherit from the abstract class "B".
So what I am struggling to do is, I want to make a single add(); method that takes B objects as parameter and adds BC objects if the parameter is BC type, and add BD objects if the parameter is BD type. Is there a correct way to do this or should I make seperate add methods?
public class A
{
private ArrayList<BC> bcArrayList= new ArrayList<>();
private ArrayList<BD> bcArrayList= new ArrayList<>();
public void add(ArrayList<B> bArrayList)
{
//m = create new object of type, either BC or BD;
bArrayList.add(m);
}
}
Joakim Danielson :
I think that if you want to add multiple objects from a list then have one method that takes a List<B>
and use instanceof
public void add(List<B> bList) {
for (B b : bList) {
if (b instanceof BC) {
bcArrayList.add((BC)b);
}
if (b instanceof BD) {
bdArrayList.add((BD)b);
}
}
}
But for adding single objects I think using method overloading is the cleanest way to do it
public void add(BC b) {
bcArrayList.add(b);
}
public void add(BD b) {
bdArrayList.add(b);
}
Of course you can add them all to your class and use them like this
A a = new A();
a.add(new BC());
a.add(new BD());
List<B> list = new ArrayList<>();
list.add(new BC());
list.add(new BD());
a.add(list);