2014-02-06 26 views
0

我知道這個問題有很多答案。但我還沒有找到解決方案。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()方法。

+0

看起來您在「equals」實現中遇到問題。 –

+2

它調用InetAddress的equals()方法嗎?這將完成同樣的事情,也許這就是它的實現。 –

+0

現在我正在檢查你的代碼,你有'List ',並且你正在檢查它是否包含'InetAddress',所以'InetAddress'不等於'IpAddressRange',因此你應該得到一個異常你的代碼。或者,您發佈的代碼錯誤。 –

回答

4

問題是您的equals()的實施不符合InetAddress的實施。 equals()方法應該是對稱的。

看一看合同here的:

equals方法實現對非空對象的引用的等價關係:

  • 自反性:對於任何非空引用值x ,x.equals(x) 應該返回true。
  • 對稱性:對於任何非空引用值 x和y,x.equals(y)應返回true當且僅當y.equals(x) 返回true。
  • 傳遞性:對於任何非空引用值x, y和z,如果x.equals(y)的返回true和y.equals(z)返回true, 那麼x.equals(z)的應返回true。
  • 它是一致的:對於任何 非空引用值x和y,的x.equals(y)多次調用 始終返回true或始終返回假,提供在不使用 信息等於在對象上比較被修改。對於 ,任何非空參考值x,x.equals(null)應該返回false。

的一點是,你也許能夠實現它像anIpAddressRange.equals(anInetAddress)回報true,而不是周圍的其他方式,因爲你不能從InetAddress編輯equals()方法。

+0

OP的比較'InetAddress'和'IpAddressRange' ... –

+0

@LuiggiMendoza:並且? –

+1

比使這個'equals'實現對稱(實際上它是合約的一部分)更重要,因爲它比InetAddress'和'InetAddress'或它們的子類(類似於'IpAddressRange')更好比較兩個*無關的*類。 –