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!
The easiest method is to have two overloads:
public void push(Obj1 obj) {
objList1.add(obj);
}
public void push(Obj2 obj) {
objList2.add(obj);
}
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.