我知道這個問題有很多答案。但我還沒有找到解決方案。ArrayList contains()沒有使用類的equals()方法
class IpAddressRange
{
InetAddress start;
InetAddress end;
public IpAddressRange(String start, String end) throws Exception
{
this.start = InetAddress.getByName(start);
this.end = InetAddress.getByName(end);
}
@Override
public boolean equals(Object input)
{
System.out.println("Inside equals");
long lv = IpAddressRange.ipToLong(start);
long hv = IpAddressRange.ipToLong(end);
if(input != null && input instanceof InetAddress)
{
long iv = IpAddressRange.ipToLong((InetAddress)input);
if(iv >= lv && iv <= hv)
return true;
}
return false;
}
@Override
public String toString()
{
return start.getHostAddress() + "-" + end.getHostAddress();
}
public static long ipToLong(InetAddress ip) {
byte[] octets = ip.getAddress();
long result = 0;
for (byte octet : octets) {
result <<= 8;
result |= octet & 0xff;
}
return result;
}
}
當我在ArrayList
使用,所以不能用equals()
方法。
ArrayList<IpAddressRange> allocatedList = new ArrayList<IpAddressRange>();
allocatedList.add(new IpAddressRange("10.10.10.10","10.10.10.12"));
下面是調用代碼:
InetAddress inetAddress1 = InetAddress.getByName("10.10.10.11");
allocatedList.contains(inetAddress1);
但這並沒有叫IpAdressRange
類的equals()
方法。
看起來您在「equals」實現中遇到問題。 –
它調用InetAddress的equals()方法嗎?這將完成同樣的事情,也許這就是它的實現。 –
現在我正在檢查你的代碼,你有'List',並且你正在檢查它是否包含'InetAddress',所以'InetAddress'不等於'IpAddressRange',因此你應該得到一個異常你的代碼。或者,您發佈的代碼錯誤。 –