4

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?

7 Answers 7

6

You should invoke the constructor :

StringPair[] p = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Sign up to request clarification or add additional context in comments.

Comments

2

Use new Operator inside {}. difference between object and variable

StringPair p[] = {
    new StringPair("a", "b"),
    new StringPair("c", "d")
};

Comments

1

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.

Comments

0

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") };

Comments

0

You need to pass object's of StringPair

like below code

StringPair p[] = { new StringPair ("a", "b"), new StringPair ("c", "d") };

Comments

0

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") };

2 Comments

mark it as answer if it solves your problem, thanks :)
how is this different from other answers? do not post duplicate answers
0

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");
    }}
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.