1

Is it possible to have a class MyClass<T> where T is a one dimensional or multidimensional array of integers? If so, and assuming that there's a field in the class of type T, how would I go about writing the equals method?

Johnny
  • 7,073
  • 9
  • 46
  • 72
  • What is your requirement that 2 `MyClass` instances are equal? – user1803551 Jul 07 '16 at 13:36
  • That all fields are equal. – Johnny Jul 07 '16 at 13:43
  • Then call the `equals` method on all of them. And as for your first question, why not check yourself? – user1803551 Jul 07 '16 at 13:46
  • That won't give the correct result. `T` is an array so calling `equals` on it will merely compare references, not do an element by element comparison. – Johnny Jul 07 '16 at 13:49
  • Then we're back to the original issue where the arguments to `Arrays.equals` are of type `Object[]` and the compiler doesn't know that `T` is an array. – Johnny Jul 07 '16 at 13:52
  • The compiler can't know what `T` is when you write the `equals` method. It only knows it once you declare it somewhere. You can check what `T` is yourself. Can you edit the question to be very specific on what you want to do and what the problem is? "How to write an equals method" is too general and explained many times on this site. – user1803551 Jul 07 '16 at 14:03

2 Answers2

1

If you don't want to switch on the actual class and handle array-of-primitives separately, you can just wrap it in one more layer of array and use Arrays.deepEquals():

Arrays.deepEquals(new Object[]{t}, new Object[]{other.t})
newacct
  • 119,665
  • 29
  • 163
  • 224
-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();
      }

   }
}
rezdm
  • 165
  • 1
  • 11
  • Doesn't work when you try to implement `equals`. If you try `Arrays.deepEquals(this._t, other._t)` the compiler can't tell that `_t` is an array, you also can't cast it with `(Object[]) _t` as it's an array of primitives. – Johnny Jul 07 '16 at 12:57
  • http://stackoverflow.com/questions/1449001/is-there-a-java-reflection-utility-to-do-a-deep-comparison-of-two-objects – rezdm Jul 07 '16 at 13:01
  • I belive that won't work either at it simply calls `equals` on every field. – Johnny Jul 07 '16 at 13:05
  • Nope. Replies there suggest serialize, compare serialized data as a possible solution. – rezdm Jul 08 '16 at 11:38