2016-07-07 79 views
1

是否有可能有一個類MyClass<T>其中T是一維或多維整數數組?如果是這樣,並假設類型爲T的類中有一個字段,那麼我將如何去編寫equals方法?是否有可能有一個泛型類的類型是一個未知維數組?

+0

什麼你需要2個'MyClass'實例是否相等? – user1803551

+0

所有字段相同。 – Johnny

+0

然後在所有這些方法上調用equals方法。至於你的第一個問題,爲什麼不檢查你自己? – user1803551

回答

1

如果你不想打開實際的類和處理數組的基元分開,你可以將它包裝在陣列中的一個多圖層,使用Arrays.deepEquals()

Arrays.deepEquals(new Object[]{t}, new Object[]{other.t}) 
-2
import java.util.*; 

public class A<T> 
{ 
    private final T _t; 
    public A(T t) { _t = t; } 
    public void doSmth() { System.out.println(_t); } 

    public static void main(String[] args) 
    { 
     { 
       A<Integer> x = new A<>(10); 
       x.doSmth(); 
     } 

     { 
      Integer[] a = new Integer[5]; 
      A<Integer[]> x = new A<>(a); 
      x.doSmth(); 
     } 

     { 
      List<Integer> a = new ArrayList<Integer>(); 
      A<List<Integer>> x = new A<>(a); 
      x.doSmth(); 
     } 

    } 
} 
+0

當您嘗試實現'equals'時不起作用。如果你嘗試'Arrays.deepEquals(this._t,other._t)'編譯器不能告訴'_t'是一個數組,你也不能用'(Object [])_t'強制轉換它,因爲它是一個基元數組。 – Johnny

+0

http://stackoverflow.com/questions/1449001/is-there-a-java-reflection-utility-to-do-a-deep-comparison-of-two-objects – rezdm

+0

我相信,不會在任何工作它只是在每個字段上調用「equals」。 – Johnny

相關問題