How to initialize a static array of objects in java

Basically, I want to create a data structure of values โ€‹โ€‹already known at compile time. In C, I would do it like this:

struct linetype { int id; char *descr; }; static struct linetype mylist[] = { { 1, "first" }, { 2, "second" } }; 

The only thing I found in Java is creating an array at runtime:

 public class Outer { public class LineType { int id; String descr; private LineType( int a, String b) { this.id = a; this.descr = b; } } LineType[] myList = { new LineType( 1, "first" ), new LineType( 2, "second" ), }; 

It seems cumbersome and inefficient (when structures become long and complex). Is there another way?

(NB: please ignore any syntax errors, as this is just a sample code created for this question. Also, I know that String is somethign else than a pointer to a character pointing to a data segment. However, the argument works with primitive data types).

+4
source share
6 answers

You should make LineType a static class:

 public class Outer { public static class LineType { int id; String descr; private LineType( int a, String b) { this.id = a; this.descr = b; } } static LineType[] myList = { new LineType( 1, "first" ), new LineType( 2, "second" ), }; } 
+6
source

If I donโ€™t get something, it should be so simple:

 Object[][] mylist = {{1, "first"}, {2, "second"}}; 
+2
source

In Java, you cannot create arrays at compile time (arrays are a special type of object). Any time you load a class using static blocks (or) runtime (as an instance variable) you can create arrays.

Static block example:

 class TestClass { static { arr[0] = "Hi"; arr[1] = "Hello"; arr[2] = "How are you?"; } .... } 
+1
source

If you want to avoid using a new object, you can use Map instead of an array. Please note that the first value (1, 2, etc.) must always be unique. See the Oracle documentation for Maps .

 private static Map<Integer, String> myMap = new TreeMap<Integer, String>(); static { myMap.put(1, "first"); myMap.put(2, "second"); } 
+1
source

If the data structure is really really dirty and complicated, and you really do not want to "clutter up" the code with it, you can create it in a completely separate small program and serialize / save it to disk. Your "real" program simply deserializes / reads it.

Of course, this really obscures what is happening, so I would avoid this technique if you really don't need it.

If the problem is only that the initial download speed of the application is slow, you can defer static initializers using the template holder

0
source

You can initialize them using static blocks in Java .

 class Outer { static { // whatever code is needed for initialization goes here } } 
-1
source

Source: https://habr.com/ru/post/1445594/


All Articles