Working with Recursion and Generic Interfaces
I have three generic interfaces (with an inverses relationship between two of them) and want to process them in a recursive method:
public interface User<R extends Role<R,U>, U extends User<R,U>>
{
public R getRole();
public void setRole(R role);
}
public interface Role<R extends Role<R,U>,U extends User<R,U>>
{
public List<R> getRoles();
public void setRoles(List<R> roles);
public开发者_StackOverflow中文版 List<U> getUser() ;
public void setUser(List<U> user);
}
Now I want to do some processing with a recursion in my Worker
class:
public <R extends Role<R,U>,U extends User<R,U>> void recursion(List<R> roles)
{
for(R role : roles)
{
recursion(role.getRoles());
}
}
I get this error and I'm didn't figured out why this does not work or how I can solve this:
Bound mismatch: The generic method recursion(List<R>) of type Worker is not
applicable for the arguments (List<R>). The inferred type User<R,User<R,U>>
is not a valid substitute for the bounded parameter <U extends User<R,U>>
I modified it, without using generic wildcards ?
, so it compiles.
After stripping out method declarations irrelevant to the problem:
public interface Role<R extends Role<R, U>, U extends User<R, U>> {
public List<Role<R, U>> getRoles(); // Change here to return type
}
public interface User<R extends Role<R, U>, U extends User<R, U>> { // No change
}
// Change to method parameter type
public static <R extends Role<R, U>, U extends User<R, U>> void recursion(List<Role<R, U>> roles) {
for (Role<R, U> role : roles) { // Change to element type
recursion(role.getRoles());
}
}
I hope these changes still fit your design - let me know if they don't work for you and I'll try to work around your requirements.
Phew! Tough one!
As you have noticed you need to specify the type U
in one of the arguments. You can do that or if you want to ignore the U
type you can use ?
instead:
public <R extends Role<R,?>> void recursion(List<R> roles)
{
for(R role : roles)
{
recursion(role.getRoles());
}
}
精彩评论