bganoush
asked on
Java static array initialize....
I tried this in one of my classes, is this possible in java? (In other words, how do you create a static list of objects without having to create it at runtime?
protected class widget {
int id;
String name;
String value;
}
private static widget[] widgetlist {
{0, "statue", "$5.95"},
{1, "vase", "$10.50"},
{2, "desk", "see master list"}
};
protected class widget {
int id;
String name;
String value;
}
private static widget[] widgetlist {
{0, "statue", "$5.95"},
{1, "vase", "$10.50"},
{2, "desk", "see master list"}
};
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Also, once you have the constructor as ksivananth mentioned, you can initialise in this way...
private static widget[] widgetlist {
new Widget(0, "statue", "$5.95"),
new Widget(1, "vase", "$10.50"),
new Widget(2, "desk", "see master list")
};
private static widget[] widgetlist {
new Widget(0, "statue", "$5.95"),
new Widget(1, "vase", "$10.50"),
new Widget(2, "desk", "see master list")
};
>>you can initialise in this way...
the problem with this is, each time you call this method, a new array created and initialized which you ultimately wouldn't want!
the problem with this is, each time you call this method, a new array created and initialized which you ultimately wouldn't want!
> each time you call this method
What method are you referring to?
What method are you referring to?
widgetlist()
???
widgetlist is a private static member, not a method!? There are no methods in what the OP posted!
widgetlist is a private static member, not a method!? There are no methods in what the OP posted!
>>widgetlist is a private static member, not a method
private static member with initialization can't be this way, it should be as I posted earlier,
private static Widget[] arr = new Widget[ 3 ] ;
static{
arr[0] = new Widget( 0, "statue", "$5.95" ) ;
arr[1] = new Widget( 1, "vase", "$10.50" ) ;
arr[2] = new Widget( 2, "desk", "see master list" ) ;
}
private static member with initialization can't be this way, it should be as I posted earlier,
private static Widget[] arr = new Widget[ 3 ] ;
static{
arr[0] = new Widget( 0, "statue", "$5.95" ) ;
arr[1] = new Widget( 1, "vase", "$10.50" ) ;
arr[2] = new Widget( 2, "desk", "see master list" ) ;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Ok, so I forgot the equals sign! :)
http://stackoverflow.com/questions/1154008/java-anyway-to-declare-an-array-in-line
http://stackoverflow.com/questions/2760995/java-arraylist-initialization