java generics with ArrayList -


i have java generics related question

i have parents class called container below: container can contain other containers , services. services class extends container can contain servicemembers extend container.

the below code doesnt work though in services class override parents class's getelements() method , return arraylist of elements subclass of container class.

any idea on how can work or using wrong way ?

public class container {    protected arraylist<container> elements = new arraylist<container>();     public arraylist<container> getelements()    {    } }  public class service extends container {   public arraylist<servicemember> getelements()   {   } } 

i think need modify container class this:

public class container<t extends container> {    protected list<t> elements = new arraylist<t>();     public list<t> getelements() {        return elements;      } } 

this allow parametrize of subclasses of container class (or itself).

the service class this:

public class service extends container<service> {  } 

at final, can instantiate objects of these classes this:

service s = new service(); arraylist<service> elements = s.getelements();  container<container> c = new container<container>(); arraylist<container> els = c.getelements();  //adding element each of lists: c.getelements().add(new container<container>()); system.out.println(c.getelements().size());  s.getelements().add(new service()); system.out.println(s.getelements().size()); 

anyway, recommend think on design, because mixing raw classes generics unsafe , confusing.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -