Creating circular generic references

Posted by M. Jessup on Stack Overflow See other posts from Stack Overflow or by M. Jessup
Published on 2010-04-02T15:49:51Z Indexed on 2010/04/02 15:53 UTC
Read the original article Hit count: 341

Filed under:
|
|

I am writing an application to do some distributed calculations in a peer to peer network. In defining the network I have two class the P2PNetwork and P2PClient. I want these to be generic and so have the definitions of:

P2PNetwork<T extends P2PClient<? extends P2PNetwork<T>>>

P2PClient<T extends P2PNetwork<? extends T>>

with P2PClient defining a method of setNetwork(T network). What I am hoping to describe with this code is:

  1. A P2PNetwork is constituted of clients of a certain type
  2. A P2PClient may only belong to a network whose clients consist of the same type as this client (the circular-reference)

This seems correct to me but if I try to create a non-generic version such as

MyP2PClient<MyP2PNetwork<? extends MyP2PClient>> myClient;

and other variants I receive numerous errors from the compiler. So my questions are as follows:

  1. Is a generic circular reference even possible (I have never seen anything explicitly forbidding it)?
  2. Is the above generic definition a correct definition of such a circular relationship?
  3. If it is valid, is it the "correct" way to describe such a relationship (i.e. is there another valid definition, which is stylistically preferred)?
  4. How would I properly define a non-generic instance of a Client and Server given the proper generic definition?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics