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?

iPherian
  • 908
  • 15
  • 38

7 Answers7

6

You should invoke the constructor :

StringPair[] p = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Eran
  • 387,369
  • 54
  • 702
  • 768
2

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

StringPair p[] = {
    new StringPair("a", "b"),
    new StringPair("c", "d")
};
Community
  • 1
  • 1
sovas
  • 1,508
  • 11
  • 23
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.

Pau
  • 14,917
  • 14
  • 67
  • 94
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") };
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

You need to pass object's of StringPair

like below code

StringPair p[] = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
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") };
Ashok Rayal
  • 405
  • 3
  • 16
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");
    }}
};
Jamie
  • 1,754
  • 16
  • 34