zer*_*n23 6 java collections ip-address
在Java中,我有一个ip地址的arrayList.我如何找到最小值和最大值?
我已经使用了Collection.min()但它不起作用给出如下情况:
192.168.0.1 <--min
192.168.0.250
192.168.0.9 <--max
Run Code Online (Sandbox Code Playgroud)
我该如何回归
192.168.0.1 <--min
192.168.0.250 <--max
Run Code Online (Sandbox Code Playgroud)
代替?
ArrayList是从数据库中检索的.我需要每次滴答做这个操作(每个滴答间隔为5秒).IP地址的数量最多可能达到300.
Sal*_*n A 13
将IP地址转换为长整数,然后对其进行排序.192.168.0.1可以使用二进制算术/运算符转换为整数:
( 192 << 24 ) + ( 168 << 16 ) + ( 0 << 8 ) + ( 1 << 0 )
Run Code Online (Sandbox Code Playgroud)
等等.请阅读以下有关使用正确数据类型的注释.
您是否将IP地址存储为String实例?这可能是这种情况,因为String按字典顺序排序,这意味着"10" < "2".
如果要以数字方式对它们进行排序,有以下几种方法:
List<String>,将它们放入List<Integer>
SortedSet<Integer>List<String>,但提供自定义比较器,将比较转换String为数值
这是一个将两者结合成一个的例子:
import java.util.*;
public class IPSorter {
static Long toNumeric(String ip) {
Scanner sc = new Scanner(ip).useDelimiter("\\.");
return
(sc.nextLong() << 24) +
(sc.nextLong() << 16) +
(sc.nextLong() << 8) +
(sc.nextLong());
}
public static void main(String[] args) {
Comparator<String> ipComparator = new Comparator<String>() {
@Override public int compare(String ip1, String ip2) {
return toNumeric(ip1).compareTo(toNumeric(ip2));
}
};
SortedSet<String> ips = new TreeSet<String>(ipComparator);
ips.addAll(Arrays.asList(
"192.168.0.1", "192.168.0.250", "192.168.0.9", "9.9.9.9"
));
System.out.println(ips);
// "[9.9.9.9, 192.168.0.1, 192.168.0.9, 192.168.0.250]"
}
}
Run Code Online (Sandbox Code Playgroud)
引用Java \xe2\x80\x93 IP 地址到整数并返回
\n\npublic static String intToIp(int i) {\n return ((i >> 24 ) & 0xFF) + "." +\n ((i >> 16 ) & 0xFF) + "." +\n ((i >> 8 ) & 0xFF) + "." +\n ( i & 0xFF);\n}\n\npublic static Long ipToInt(String addr) {\n String[] addrArray = addr.split("\\\\.");\n\n long num = 0;\n for (int i=0;i<addrArray.length;i++) {\n int power = 3-i;\n\n num += ((Integer.parseInt(addrArray[i])%256 * Math.pow(256,power)));\n }\n return num;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n从数据库中检索 IP 地址字符串,我将所有内容转换为 ArrayList,然后应用 Collection.min() \n然后将 long 转换回 int,然后再转换回 String。获取 IP 地址的排序字符串。
\n\n谢谢
\n