Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize array of custom class

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?

like image 345
iPherian Avatar asked Jan 04 '23 03:01

iPherian


2 Answers

You should invoke the constructor :

StringPair[] p = { new StringPair ("a", "b"), new StringPair ("c", "d") };
like image 62
Eran Avatar answered Jan 13 '23 16:01

Eran


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

StringPair p[] = {
    new StringPair("a", "b"),
    new StringPair("c", "d")
};
like image 29
sovas Avatar answered Jan 13 '23 14:01

sovas