Reputation: 41
Is there any way to initialize a data structure to constant values in Java? I've searched high and low and can't find any such technique. I specifically want to initialize a class which contains mixed data types, such as String and int.
class xyz {
String a;
int b;
}
static final xyz example1 = { "string value", 42 }; // This doesn't work.
static final xyz[] example2 = { { "value a", 42 }, { "value b", 43 } }; // this also doesn't work
I can initialize arrays of String, even two-dimensional arrays of String, but for some reason I cannot initialize a record structure or an array of record structures. I do this routinely in Delphi and find it very difficult to live without this feature.
Okay, I've been programming for about 40 years, so I am not exactly a newbie. I need to know if something like this is possible. I do want the constant data embedded in my app, not read in from a file, and using assignment statements to set up the data kind of defeats the purpose of declaring them as constants (final).
Thanks for any suggestions or comments. I really would like to find a good solution to this problem as I have a lot of Pascal code to convert to Java and I don't want to have to redesign all the data structures.
Upvotes: 4
Views: 8463
Reputation: 328735
If you don't want to use a constructor or a static block as proposed in other answers, you can use the double brace initialization syntax:
static final xyz example1 =
new xyz() {{ a = "string value"; b = 42; }};
Note that it creates an anonymous class.
Your second example would look like:
static final xyz[] example1 = new xyz[] {
new xyz() {{ a = "value a"; b = 42; }},
new xyz() {{ a = "value b"; b = 43; }}
};
However, if you have access to the xyz
class, adding a constructor that takes two parameters would be more readable and (slightly) more efficient.
Upvotes: 9
Reputation: 19185
You can use Enums for this
enum xyz {
VALUE_A("value a", 42), VALUE_B("value b", 43);
String a;
int b;
xyz(String str, int value) {
a = str;
b = value;
}
static EnumSet<xyz> bothValues = EnumSet.of(xyz.VALUE_A, xyz.VALUE_B);
}
Upvotes: 0
Reputation: 178481
You can either write a constructor xyz(String,int)
or use the default constructor and initialize the values in a static
block:
static final xyz example1 = new xyz();
static {
example1.a = "string value";
example1.b = 42;
}
Note: you should have access to the fields in the initializing class.
Also note: if xyz
is an inner class - you will probably need to declare it as static
for the above code to work.
P.S. The java convention is using an upper case letter as the first letter in a class name, so it should probably be renamed to Xyz
Upvotes: 0
Reputation: 66657
One way is write constructor for xyz
class to achieve what you want.
class xyz {
String a;
int b;
xyz(String tempStr, int tempInt)
{
this.a = tempStr;
this.b = tempInt;
}
}
static final xyz example1 = new xyz("String value", 42);
Upvotes: 3