java - How to create a collection of different types objects to use it with polymorphis -


i have problem different type of objects in collection, in case arraylist, here there example:

public interface customobject {} public class customobjecta implements customobjects {} public class customobjectb implements customobjects {} 

in main call mymethod:

arraylist<customobject> list = new arraylist<>();  for(int i=0; < list.size(); i++) {    mymethod(list.get(i)); } 

mymethod defined overloading written below:

public void mymethod(customobjecta a) { ... } public void mymethod(customobjectb b) { ... } 

there compile-error. how can solve? what's right way (collections, generics, wildcard ?)

one way work around use of visitor pattern, allows attach functionality, without touching domain objects

// visitor, can 'visit' types interface customobjectvisitor {     void visita(customobjecta a);     void visitb(customobjectb b); }  // make customobject visitee public interface customobject {     void accept(customobjectvisitor visitor); }  // implement classes accept method public class customobjecta implements customobject {     @override public void accept(customobjectvisitor visitor) {         visitor.visita(this);     } } public class customobjectb implements customobject {     @override public void accept(customobjectvisitor visitor) {         visitor.visitb(this);     } } 

now can make main class visitor this:

public class main implements customobjectvisitor {     public void methodthatdidntworkbefore() {         arraylist<customobject> list = new arraylist<>();         for(customobject obj: list) {             obj.accept(this);         }     }      @override public void visita(customobjecta a) { ... }     @override public void visitb(customobjectb b) { ... } } 

check out wikipedia too, it's useful once wrap head around it.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -