I'd like to initialize an array of objects (contrived example)
class StringPair {
String a;
String b;
// constructor
}
StringPair p[] = {
{ "a", "b" },
{ "c", "d" }
};
But javac complains java: illegal initializer for StringPair
for definition of p
How should I write this?
You should invoke the constructor :
StringPair[] p = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Use new
Operator inside {}.
difference between object and variable
StringPair p[] = {
new StringPair("a", "b"),
new StringPair("c", "d")
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With