给定一个IP地址列表,你如何找到最小,最大? [英] Given a list of IP address, how do you find min, max?
问题描述
在Java中,我有一个ip地址的arrayList。如何找到最小和最大?
In Java, i have an arrayList of ip address. how do i find the min and max ?
我使用了Collection.min(),但它没有工作给定的情况下:
I have used the Collection.min() but it doesnt work given a case like :
192.168.0.1 <--min
192.168.0.250
192.168.0.9 <--max
如何返回
192.168.0.1 <--min
192.168.0.250 <--max
从数据库检索ArrayList。我需要对每个tick做这个操作(每个tick是在5秒间隔)。
ArrayList is retrieve from the database. I would need to do this operation per tick (each tick is at 5 sec interval). The number of IP address would hit a max of probably 300.
推荐答案
public static String intToIp(int i) {
return ((i >> 24 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
((i >> 8 ) & 0xFF) + "." +
( i & 0xFF);
}
public static Long ipToInt(String addr) {
String[] addrArray = addr.split("\\.");
long num = 0;
for (int i=0;i<addrArray.length;i++) {
int power = 3-i;
num += ((Integer.parseInt(addrArray[i])%256 * Math.pow(256,power)));
}
return num;
}
从数据库检索Ip地址字符串,我将所有转换为ArrayList,然后应用Collection.min()
然后我将long转换回int,然后回到String。获取排序的ip地址字符串。
Retrieving from the database the Ip address String, I converted all to a ArrayList and then apply the Collection.min() Then I convert back the long to int and then back to String. To obtain a sorted String of ip addresses.
感谢
这篇关于给定一个IP地址列表,你如何找到最小,最大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!