2017-06-01 138 views
3

假設我有一個通用的容器類型這樣的:如何爲泛型類型實現equals?

public final class Container<T> { 

    public final T t; 

    public Container(final T t) { 
     this.t = t; 
    } 
} 

我想要實現等於使得該通行證:

final Container<Object> a = new Container<>("Hello"); 
final Container<String> b = new Container<>("Hello"); 

assertNotEquals(a, b); 

的情況下ab應該是不同的,因爲它們的類型參數T是不同。

但是,由於擦除,這是很難做到的。此實現,例如,不正確:

@Override 
public boolean equals(final Object obj) { 
    if (this == obj) { 
     return true; 
    } 
    if (obj != null && obj instanceof Container<?>) { 
     final Container<?> other = (Container<?>)obj; 
     return Objects.equals(this.t, other.t); 
    } 
    return false; 
} 

我期望我會需要存儲一些類型的令牌爲T

如何爲泛型類型實現equals?


This不回答這個問題。

+1

它確實無關w刪除。如果你使用數組,沒有擦除,比如'Object [] a = {「Hello」}; String [] b = {「Hello」};','a [0] .equals(b [0])'仍然會返回'true'。 equals操作使用對象的運行時類型。 – RealSkeptic

回答

3

可以修改一個小容器類,並添加這一領域:

public final Class<T> ct; 

與和平等覆蓋然後

System.out.println(a.equals(b)); 

將返回false因爲equals方法將檢查Class<String> VS Class<Object>

class Container<T> { 

    public final T t; 
    public final Class<T> ct; 

    public Container(final T t, Class<T> ct) { 
     this.t = t; 
     this.ct = ct; 
    } 

    @Override 
    public int hashCode() { 
     final int prime = 31; 
     int result = 1; 
     result = (prime * result) + ((ct == null) ? 0 : ct.hashCode()); 
     result = (prime * result) + ((t == null) ? 0 : t.hashCode()); 
     return result; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if (this == obj) 
      return true; 
     if (obj == null) 
      return false; 
     if (getClass() != obj.getClass()) 
      return false; 
     Container other = (Container) obj; 
     if (ct == null) { 
      if (other.ct != null) 
       return false; 
     } else if (!ct.equals(other.ct)) 
      return false; 
     if (t == null) { 
      if (other.t != null) 
       return false; 
     } else if (!t.equals(other.t)) 
      return false; 
     return true; 
    } 

} 
+0

有沒有一種方法可以消除「新容器(」a「,String.class)'的鍋爐板?這仍然適用於'Container >'? – sdgfsdh

+1

你應該熟悉'Objects.hash()',它確實實現了你的'hashCode()'的實現,所以你的方法變成了'返回Objects.hash(ct,t);' – Bohemian