Accessing functions from Java Generics

Even If we had 2 or more classes w/ the exactly same code, Java would still “see” them as different from each:

void setup() {
  MyVec vec1 = new MyVec();
  MyVecTwin vec2 = new MyVecTwin();

  println(MyVec.class.isInstance(vec1)); // true
  println(MyVec.class.isInstance(vec2)); // false

  exit();
}

class MyVec {
  float x = random(-100, 100), y = random(-100, 100), z;

  @Override String toString() {
    return "[ " + x + ", " + y + ", " + z + " ]";
  }
}

class MyVecTwin { // exactly same code as class MyVec
  float x = random(-100, 100), y = random(-100, 100), z;

  @Override String toString() {
    return "[ " + x + ", " + y + ", " + z + " ]";
  }
}

So it doesn’t matter if a class got structurally the same members as another 1; under Java’s PoV, they’re not the same! :crazy_face:

In my previous reply, I’ve instantiated a Comparator which can be used to sort() any array or list of objects which implements the DoubleSupplier datatype.

If we needed to sort() a container of PVector objects instead, we’d need to change the Comparator’s generic datatype DoubleSupplier to PVector.

Plus, switch method DoubleSupplier::getAsDouble() to field PVector::x inside method Comparator::compare()'s implementation:

import java.util.Comparator;
import java.util.Arrays;
//import java.util.Collections;

static final Comparator<PVector> ASCENT_X = new Comparator<PVector>() {
  @Override final int compare(final PVector v1, final PVector v2) {
    return (int) Math.signum(v1.x - v2.x);
  }
};

Still, we couldn’t sort() neither an array of MyVec nor of MyVecTwin w/ the Comparator<PVector> above; even though they’ve both got the field x in common, just like a PVector: :disappointed:

import java.util.Comparator;
import java.util.Arrays;
//import java.util.Collections;

static final Comparator<PVector> ASCENT_X = new Comparator<PVector>() {
  @Override final int compare(final PVector v1, final PVector v2) {
    return (int) Math.signum(v1.x - v2.x);
  }
};

final PVector[] vecs = {
  PVector.random2D(this).mult(100), 
  PVector.random2D(this).mult(100), 
  PVector.random2D(this).mult(100)
};

final MyVec[] myVecs = { new MyVec(), new MyVec(), new MyVec() };

class MyVec {
  float x = random(-100, 100), y = random(-100, 100), z;

  @Override String toString() {
    return "[ " + x + ", " + y + ", " + z + " ]";
  }
}

void setup() {
  println(vecs);
  Arrays.sort(vecs, ASCENT_X);
  println(vecs);
  println();

  println(myVecs);
  //Arrays.sort(myVecs, ASCENT_X); // Error: MyVec isn't a PVector!!!
  //println(myVecs);

  exit();
}