Mixed Datatype Arrays

  • The only way in pure Java is to go w/ datatype Object.
  • However, in order to read each element from such container, we need to (cast) each element back to its actual datatype.
  • Which of course is not very practical; and therefore, not recommended.
  • The alternative is to create a class containing all the needed datatypes as fields.
// https://Discourse.Processing.org/t/mixed-datatype-arrays/14673/5
// GoToLoop (2019-Oct-13)

final Mixed[] mix = {
  new Mixed("hello", 1, 2, 3.5), 
  new Mixed("mixed", -1, -2, -3.5), 
  new Mixed("types", MAX_INT, MIN_INT, 1e-3)
};

void setup() {
  printArray(mix);
  exit();
}

class Mixed {
  String txt;
  int a, b;
  float f;

  Mixed(String txt, int a, int b, float f) {
    this.txt = txt;
    this.a = a;
    this.b = b;
    this.f = f;
  }

  String toString() {
    return txt + ", " + a + ", " + b + ", " + f;
  }
}
4 Likes