Reputation: 1058
I have a bit of confusion in the following:
class Foo{
private ArrayList<Obj1> obj1List;
private ArrayList<Obj2> obj2List;
/* constructor */
...
public void push(?){
if(the object is of type Obj1)
push into obj1List (object)
if(the object is of type Obj2)
push into obj2List (object)
}
How can I do such a thing with the Push function, that it would identify the object type itself, without using instanceof (casting) or using (Object obj) as its' parameter? I need to it to know into which arraylist to push!
Upvotes: 0
Views: 41
Reputation: 500357
The easiest method is to have two overloads:
public void push(Obj1 obj) {
objList1.add(obj);
}
public void push(Obj2 obj) {
objList2.add(obj);
}
Upvotes: 4
Reputation: 328608
You can simply have 2 methods, one for each object type, and your program will use the method that is the most specific automatically:
public void push(Obj1 obj){
obj1List.add(obj);
}
public void push(Obj2 obj){
obj2List.add(obj);
}
Upvotes: 1