I need to write Comparator for InetSocketAddress so I can use this class in a TreeSet. They need to be comparable by address and port.
The code would look something like this, but the problem is I don’t know how to compare addresses and ports by <(-1),>(1),=(0)
TreeSet<InetSocketAddress> _tree = new TreeSet<InetSocketAddress>
(new Comparator<InetSocketAddress>() {
public int compare(InetSocketAddress o1, InetSocketAddress o2) {
///?????
return 0;
}
});
Edit… the actual question. How to compare InetSocketAddress.
Codes with InetSocketAddress#getHostName comparation is incorrect because when hostname is resolved it can be null. Look at constructor:
The code wchich uses only IP is incorrect too – hostname can be unresolved. This should be quite efficient: