Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing data structures to constant values with mixed data types

Tags:

java

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.

like image 546
user1698044 Avatar asked Dec 16 '22 19:12

user1698044


1 Answers

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.

like image 165
assylias Avatar answered Jan 17 '23 13:01

assylias