gpt4 book ai didi

InetSocketAddress 的 Java 比较器

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:01:12 24 4
gpt4 key购买 nike

我需要为 InetSocketAddress 编写 Comparator,这样我就可以在 TreeSet 中使用此类。它们需要通过地址和端口进行比较。

代码看起来像这样,但问题是我不知道如何通过 <(-1),>(1),=(0) 比较地址和端口

TreeSet<InetSocketAddress> _tree = new TreeSet<InetSocketAddress> 
(new Comparator<InetSocketAddress>() {

public int compare(InetSocketAddress o1, InetSocketAddress o2) {

///?????
return 0;
}
});

编辑...实际问题。如何比较 InetSocketAddress。

最佳答案

与 InetSocketAddress#getHostName 比较的代码是不正确的,因为解析主机名时它可能为空。查看构造函数:

public InetSocketAddress(String hostname, int port) {
if (port < 0 || port > 0xFFFF) {
throw new IllegalArgumentException("port out of range:" + port);
}
if (hostname == null) {
throw new IllegalArgumentException("hostname can't be null");
}
try {
addr = InetAddress.getByName(hostname);
} catch(UnknownHostException e) {
this.hostname = hostname;
addr = null;
}
this.port = port;
}

仅使用 IP 的代码也不正确 - 主机名可能无法解析。这应该是非常有效的:

Integer getIp(InetSocketAddress addr) {
byte[] a = addr.getAddress().getAddress();
return ((a[0] & 0xff) << 24) | ((a[1] & 0xff) << 16) | ((a[2] & 0xff) << 8) | (a[3] & 0xff);
}

public int compare(InetSocketAddress o1, InetSocketAddress o2) {
//TODO deal with nulls
if (o1 == o2) {
return 0;
} else if(o1.isUnresolved() || o2.isUnresolved()){
return o1.toString().compareTo(o2.toString());
} else {
int compare = getIp(o1).compareTo(getIp(o2));
if (compare == 0) {
compare = Integer.valueOf(o1.getPort()).compareTo(o2.getPort());
}
return compare;
}
}

关于InetSocketAddress 的 Java 比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6644738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com