Is there a way to have various datatypes in one array? Checking online it says to initialise as an Object type but that doesn’t seem to work with processing. Can’t seem to find anything in the docu either
The Goal:
datatype[][] arrayA = {“hello”,1,2,3.5};
1 Like
Being a strong typed language based on java processing doesnt allow multiple types in one array, there are alternatives though not as easily implemented as in a language such as javascript.
https://www.techiedelight.com/return-multiple-values-method-java/
2 Likes
Ah that’s frustrating, coming from Javascript it’s annoying you can’t do that - Many thanks though!
Essentially you have to create a separate class to handle your multiple type data, you can then create an array or array list with the type defined by your class, and you can then call the values.
2 Likes
- 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
I know the feeling, things that are so easy in JavaScript, require so much depth of understanding about the java language to implement in java.
This is exactly what is needed!