Basically I want to create a data structure of values already known at compile time. In C I'd do it like this:
struct linetype { int id; char *descr; };
static struct linetype mylist[] = {
{ 1, "first" },
{ 2, "second" }
};
The only soultion I have found in Java involves creating the 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" ),
};
This appears cumbersome and ineffective (when the structures get long and complex). Is there another way?
(NB: please disregard any syntax errors as this is only sample code created for this question. Also, I am aware a String is somethign else than a character pointer pointing into the data segment. However, the argument works with primitive data types as well).
One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.
An array that is declared with the static keyword is known as static array. It allocates memory at compile-time whose size is fixed. We cannot alter the static array. If we want an array to be sized based on input from the user, then we cannot use static arrays.
Java array can also be used as a static field, a local variable, or a method parameter. The size of an array must be specified by int or short value and not long.
static final int[] a = { 100,200 }; B. C. static final int[] a = new int[2]{ 100,200 };
You have to 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" ),
};
}
In Java, you can't create arrays at compile time (arrays are special type of objects). Either class load time using static blocks (or) runtime (as instance variable) you can create arrays.
Example static block:
class TestClass
{
static {
arr[0] = "Hi";
arr[1] = "Hello";
arr[2] = "How are you?";
}
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With