I want to define objects in an array like this:
{name: "name", temp: 123, ...}
How would I do this?
-Grim
I want to define objects in an array like this:
{name: "name", temp: 123, ...}
How would I do this?
-Grim
Are you talking about Java or JavaScript?
You could create a class
for those properties:
class Stuff {
constructor(name, temp) {
this.name = name, this.temp = temp;
}
}
I am talking about Java.
Well, I did. I made a class.
I doesn’t work for Java I don’t think.
Well, the curly {}
syntax is JS. Therefore I’ve replied to you assuming it was JS!
Is there anything like this in Java?
Yes, the JS class
code below:
class Stuff {
constructor(name, temp) {
this.name = name, this.temp = temp;
}
}
Would be like this in Java Mode:
class Stuff {
String name;
int temp;
Stuff(String name, int temp) {
this.name = name;
this.temp = temp;
}
}
I meant the curly bracket definitions.
Java creates objects exclusively via classes and the operator new
.
JS is more flexible. But still I like the class
approach better, even in JS.
Alrighty then. Thanks for the help!
Java doesn’t have the syntax you’re talking about.
But note that if you have a class with a constructor:
class MyClass{
String name;
int temp;
public MyClass(String name, int temp){
this.name = name;
this.temp = temp;
}
}
Then you can call that constructor and place the instances in an array, like this:
MyClass[] myArray = { new MyClass("name", 123), new MyClass("Grimtim10", 42) }
Shameless self-promotion: here is a guide on creating classes in Processing:
Hi @Grimtin10!
What you’re referring to is called a hashmap in Java, dictionary in Python, and kind of similar to JSON in JavaScript. In Java, you can use the HashMap data structure:
HashMap<String, Object> dict= new HashMap<String, Object>();
void setup() {
size(400, 400);
dict.put("name", "Grimtin10");
dict.put("temp", 123);
println(dict);
println(dict.get("name"));
println(dict.get("temp"));
}