日期:2014-05-19 浏览次数:20779 次
Comparator compare = new Comparator(){ public int compare(Object obj1, Object obj2){ String[] ips1 = obj1.toString().split("\\."); String[] ips2 = obj2.toString().split("\\."); if(Integer.parseInt(ips1[0].toString()) != Integer.parseInt(ips2[0].toString())){ if(Integer.parseInt(ips1[0].toString()) > Integer.parseInt(ips2[0].toString())){ return 1; }else{ return 0; } }else if(Integer.parseInt(ips1[1].toString()) != Integer.parseInt(ips2[1].toString())){ if(Integer.parseInt(ips1[1].toString()) > Integer.parseInt(ips2[1].toString())){ return 1; }else{ return 0; } }else if(Integer.parseInt(ips1[2].toString()) != Integer.parseInt(ips2[2].toString())){ if(Integer.parseInt(ips1[2].toString()) > Integer.parseInt(ips2[2].toString())){ return 1; }else{ return 0; } }else{ if(Integer.parseInt(ips1[3].toString()) > Integer.parseInt(ips2[3].toString())){ return 1; }else{ return 0; } } } }; List<String> list = new ArrayList<String>(); list.add("192.168.2.1"); list.add("192.165.2.11"); list.add("192.156.2.5"); list.add("192.109.2.16"); Collections.sort(list, compare); for (String string : list) { System.out.println(string); }
------解决方案--------------------
可以转成long来比较
long ip = 192*1000000000000 + 168*100000000 + 2*1000 + 1;
------解决方案--------------------
List<String> list = new ArrayList<String>(); list.add("192.168.2.1"); list.add("192.168.2.2"); list.add("192.168.2.3"); list.add("192.168.2.16"); list.add("192.168.2.5"); list.add("192.168.2.17"); list.add("122.168.2.11"); list.add("172.168.2.12"); list.add("122.168.2.1"); list.add("172.168.2.5"); Collections.sort(list,new Comparator(){ public int compare(Object o1,Object o2) { String[] ips1 = o1.toString().split("\\."); String[] ips2 = o2.toString().split("\\."); long ip1 = (Long.parseLong(ips1[0])*1000000000 + Long.parseLong(ips1[1])*1000000 + Long.parseLong(ips1[2])*1000 + Long.parseLong(ips1[3])); long ip2 = (Long.parseLong(ips2[0])