Reputation: 33
I have the following code snippet for primitives array instantiation
int[] a = new int[] {10, 20, 30}
Is it possible to do the same for any Object Array instantiation ? Something like ..
public class MyObject {
int a;
char b;
}
And then:
public class Main(){
public static void main(String[] args){
MyObject[] = new MyObject[] { {10, 'a'}, {20, 'b'}}
}
}
Upvotes: 1
Views: 76
Reputation: 321
Make a contructor in your MyObject
class:
public MyObject(int x, char c) {
// comment: set them equal to the variables you put up in your MyObject class already
}
Then you can create an object in your Main
class:
MyObject object1 = new MyObject(10, 'a');
Then place object1
in the array: array[0] = object1
.
Or you can can store the new MyObject(10, 'a')
directly into the array - but it might be a bit harder to understand if you are new to it.
Upvotes: 0
Reputation: 671
You have to declare one constructor in the class.
public class MyObject {
int a;
char b;
MyObject(int a, char b){
this.a = a;
this.b = b;
}
}
After that you can initialize array like this
MyObject[] somedamn = new MyObject[] { new MyObject(10,'a'), new MyObject(20,'b')};
Upvotes: 2
Reputation: 24344
Not implicitly. You would have to use constructor for the initialization of each object. Here is an example:
public class Example {
static class MyObject {
int a;
char b;
public MyObject(int a, char b) {
this.a = a;
this.b = b;
}
}
public static void main(String[] args) {
MyObject[] objs = new MyObject[] {new MyObject(10, 'a'), new MyObject (20, 'b')};
}
}
Upvotes: 6
Reputation: 394016
You'll need to write the appropriate constructor in the MyObject
class (which takes int
and char
arguments and initializes the members a
and b
) and then initialize the array with:
MyObject[] arr = new MyObject[] {new MyObject(10, 'a'), new MyObject (20, 'b')};
Upvotes: 3