Reputation: 958
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?
Upvotes: 4
Views: 3175
Reputation: 1922
I don't know why so many people keep posting the same solution.
In my case, I needed to initialize an array of objects. However, these objects were generated from XSD, so I'm not able to add a custom constructor. We'd need C# with partial classes for that.
Pau above gave me the hint to solve it, but his solution doesn't compile. Here's one that does:
StringPair p[] = new StringPair[] {
new StringPair(){{
setA("a");
setB("b");
}},
new StringPair(){{
setA("c");
setB("d");
}}
};
Upvotes: 0
Reputation: 16106
If you are not able to create a constructor with params, you could use double brace initialization:
StringPair p[] = {
new StringPair(){{
setA("a");
setB("b");
}},
new StringPair(){{
setA("c");
setB("d");
}}
};
It seems like something you are looking for.
Upvotes: 1
Reputation: 405
You should Create a constructor like this
class StringPair {
String a;
String b;
Public StringPair(string a, string b)
{
this.a=a;
this.b=b;
}
}
then you can initialize it like this
StringPair p[] = { new StringPair("a", "b"), new StringPair("c", "d") };
Upvotes: 0
Reputation: 5711
You need to pass object's of StringPair
like below code
StringPair p[] = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Upvotes: 0
Reputation: 48278
following list initialization (name taken from C++) is not a valid java way to init an array:
StringPair p[] = {
{ "a", "b" },
{ "c", "d" }
};
do instead use the constructor of your class:
StringPair p[] = { new StringPair("a", "b"), new StringPair("1", "g") };
Upvotes: 0
Reputation: 1578
Use new
Operator inside {}.
difference between object and variable
StringPair p[] = {
new StringPair("a", "b"),
new StringPair("c", "d")
};
Upvotes: 2
Reputation: 393856
You should invoke the constructor :
StringPair[] p = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Upvotes: 6