java 按ip排序_Java如何对IP地址列表进行排序 (Java how to sort a list of IP Address)

The proper way is to use a comparator and generics (as outlined by folks earlier). Note that there is a fallacy of accepting the input data as being absolutely according to what you expect. For example in the case of IPs: 127.0.0.1 and 127.0.0.01 are both accepted by the Java Socket APIs. But the sort that you write should take care of these considerations as well. Therefore I recommend you to use a sorting based on the bytes (octets) of the ip address.

There are a lot of examples doing that and I would not go into that. A simple search would lead you to one on this very website.

What I would do instead is to demonstrate the need to sort by octets:

byte[] ipAddr1 = new byte[] { x1, x2, (byte) 010, x4 };

byte[] ipAddr2 = new byte[] { x1, x2, 9, x4 };

InetAddress addr = InetAddress.getByAddress(ipAddr1);

InetAddress addr = InetAddress.getByAddress(ipAddr2);

Both of these are accepted by the Java Socket library without it reporting any errors. They both work but if you sort it without taking into consideration of the individual octets (do a string sort for example) then the result might not be what you expect. Try it out and see.

For example (if you follow a Collections.sort(list) approach): if you have: "192.160.010.1" and "192.160.9.1". You would see the former appear as less than the latter but that is not true. The reason is that this will do a sort based on strings. That has nothing to do with the structure of an IP address.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值