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
  • 858
  • 13
  • 36

7 Answers7

6

You should invoke the constructor :

StringPair[] p = { new StringPair ("a", "b"), new StringPair ("c", "d") };
Eran
  • 374,785
  • 51
  • 663
  • 734
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,418
  • 10
  • 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
  • 13,250
  • 13
  • 60
  • 88
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 ツ
  • 45,713
  • 17
  • 64
  • 91
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,442
  • 4
  • 27
  • 38
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
  • 375
  • 2
  • 15
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,582
  • 16
  • 30