Java Generics and Collections: Speed Up the Java Development Process

Author: Maurice Naftalin, Philip Wadler
3.9
All Stack Overflow 10

Comments

by anonymous   2017-08-20

Read the Angelika Langer FAQ About Generics you will most likely find answers to all your questions there.

The book The Java Programming Language 4th Edition contains a good chapter on the subject.

And of course there is no better reference than the Java Language Specification which you can get for free.

The book Java Generics and Collections is also a very good book on the subject if you really intend to go that deep. I found a PDF version of the book here. Unfortunately it only contains a few pages.

by anonymous   2017-08-20

Circular generic references are indeed possible. Java Generics and Collections includes several examples. For your case, such a specimen would look like this:

public interface P2PNetwork<N extends P2PNetwork<N, C>,
                            C extends P2PClient<N, C>> {
  void addClient(C client);
}

public interface P2PClient<N extends P2PNetwork<N, C>,
                            C extends P2PClient<N, C>> {
  void setNetwork(N network);
}

class TorrentNetwork implements P2PNetwork<TorrentNetwork, TorrentClient> {
  @Override
  public void addClient(TorrentClient client) {
    ...
  }
}

class TorrentClient implements P2PClient<TorrentNetwork, TorrentClient> {
  @Override
  public void setNetwork(TorrentNetwork network) {
    ...
  }
}

...

TorrentNetwork network = new TorrentNetwork();
TorrentClient client = new TorrentClient();

network.addClient(client);
by anonymous   2017-08-20

They are entirely different constructs. A HashMap is an implementation of Map. A Map maps keys to values. The key look up occurs using the hash.

On the other hand, a HashSet is an implementation of Set. A Set is designed to match the mathematical model of a set. A HashSet does use a HashMap to back its implementation, as you noted. However, it implements an entirely different interface.

When you are looking for what will be the best Collection for your purposes, this Tutorial is a good starting place. If you truly want to know what's going on, there's a book for that, too.