I'm attempting to create a generics relationship in java between two classes which contain each other. The objects essentially form an alernating layer tree. So far, the closest SO issue i found was this: Java generics of generics of, which was close and somewhat helpful for my issue, but still different enough that I'd like additional guidance. Here's the situation or rather, what I'd like it to be:
abstract class Group<I extends Item<Group<I>>>{
private List<I> items;
public List<I> getItems(){...}
public void setItems(List<I> items){...}
}
abstract class Item<G extends Group<Item<G>>>{
private List<G> subGroups;
public List<G> getSubGroups(){...}
public void setSubGroups(List<G> subGroups){...}
}
Beyond the getters and setters, there are aspects of the class that make them notably different from each other, but the inclusion should follow like that. The reason behind this is that I want to enforce that if I have implementing classes, they have to behave like this:
class AGroup extends Group<AItem>{...} //works
class AItem extends Item<AGroup>{...} //works
class BGroup extends Group<BItem>{...} //works
class BItem extends Item<BGroup>{...} //works
class MixedGroup extends Group<AItem>{...} //fails since AItem does
//not extend Item<MixedGroup>
So far, the compiler is fine with
abstract class Group<I extends Item<Group<I>>>{
private List<I> items;
public List<I> getItems(){...}
public void setItems(List<I> items){...}
}
abstract class Item<G extends Group>{ //raw types warning
private List<G> subGroups;
public List<G> getSubGroups(){...}
public void setSubGroups(List<G> subGroups){...}
}
This mostly covers what I'm looking for since I can know that I can get a group's items' child groups and get the same kind of group back. But the compiler don't know that if I get an item's groups' items I'll get the same kind of item back (for instance, the item could be an orphan). Also, the raw types warning always makes me feel like I'm doing something wrong. Also also, if there's a better way of enforcing this kind of class binding, I'd be interested to hear it.