Constructors when creating a array of Objects [duplicate] - java

This question already has answers here:
How to initialize an array in Java?
(11 answers)
Closed 6 years ago.
When I'm creating an array of objects, how can I add the argument for the constructor inside each object? Like this:
foos = new Foo[10];
How do I make 10 objects with their constructors? I do not understand where do I put the arguments that is passed to the constructors of every object?

foos = new Foo[10];
creates an array that can hold references to 10 Foo instances. However, all the references are initialized to null.
You must call the constructor for each element of the array separately, at which point you can specify whatever argument you wish :
foos[0] = new Foo (...whatever arguments the constructor requires...);
...

This is just the allocation for a new array object of type Foo to hold multiple elements. In order to create and store actual object you will do something like this:
foos[0]=new Foo(); //Call constructor here
.
.
.
foos[10]= new Foo(); //Call constructor here

foos = new Foo[10];
This is create an array type Foo, this is not creating object
for Initializing do following:
for(int i=0;i<foos.length; i++){
foos[i] = new Foo (your-argument);
}
See Arrays for more details

You can do it inline like so:
Foo[] foos = new Foo[] {
new Foo(1),
new Foo(2),
new Foo(10)
};
Or like so:
Foo[] foos = {
new Foo(1),
new Foo(2),
new Foo(10)
};

let's say that Foo take a String as an argument so the constructor for Foo is something like this:
public Foo(String arg){
this.arg = arg;
}
if arguments you need to pass to the constructors are different from each other, so you will need to use separate initialization for every element. as #Sanjeev mentioned but with passing an argument.
foos[0]=new Foo(argOne);
.
.
foos[10]= new Foo(argTen);
on the other hand if your arguments are related to to an array index, you should use loop as #Sumit mentioned
for(int i=0;i<foos.length; i++){
foos[i] = new Foo (arg + i);
}

So in order to create "10" new objects you need to create the array to hold the objects and then loop over the list while adding a new object to each index of the array.
int foosSize = 10;
Foo[] foos = new foos[foosSize];
for(int i = 0; i < foosSize; i++) {
foos[i] = new Foo();
}
this will create a new foo object and add it to the index in the array you have created.

Related

Initializing an object in an array with a default value - java

Is there a way to define a default value for an object in array to be initialized with?
In the same way that primitive types are initialized when declaring an array of them:
int[] myIntArray = new int[5]; // we now have an array of 5 zeroes
char[] myCharArray = new char[2]; // an array in which all members are "\u0000"
etc.
I'd like to declare an array of objects of a type that I've defined, and have them automatically initialize in a similar fashion.
I suppose this would mean I'd like to run new myObject() for each index in the array (with the default constructor).
I haven't been able to find anything relevant online, the closest I got was to use Arrays.fill(myArray, new MyObject()) after initializing the array (which actually just creates one object and fills the array with pointers to it), or just using a loop to go over the array and initialize each cell.
thank you!
EDIT: I realized this is relevant not just to arrays, but for declaring objects in general and having them default to a value / initialize automatically.
The Java 8 way:
MyObject[] arr = Stream.generate(() -> new MyObject())
.limit(5)
.toArray(MyObject[]::new);
This will create an infinite Stream of objects produced by the supplier () -> new MyObject(), limit the stream to the total desired length, and collect it into an array.
If you wanted to set some properties on the object or something, you could have a more involved supplier:
() -> {
MyObject result = new MyObject();
result.setName("foo");
return result;
}
Do this so you can initialize the array when declaring it:
int[] myIntArray = {0, 0, 0,0,0};
char[] myCharArray = { 'x', 'p' };
you could of course do:
int[] myIntArray = new int[5];
and the in a for loop set all indexes to the initial value... but this can take a while if the array is bigger...
Edit:
for custom objects is the same just use an anonymous constructor in the init
Example:
public class SOFPointClass {
private int x;
private int y;
public SOFPointClass(int x, int y) {
this.x = x;
this.y = y;
}
// test
public static void main(String[] args) {
SOFPointClass[] pointsArray = { new SOFPointClass(0,0) , new SOFPointClass(1,1)};
}
}
I don't see a way that Java provides to do this.
My suggestion would be define a function to do it.
Object[] initialize(Class aClass, int number) throws IllegalAccessException, InstantiationException {
Object[] result = new Object[number];
for (int i = 0; i < number; ++i) {
result[i] = aClass.newInstance();
}
}
Then call it as Object[] arr = initialize(YourClass.class, 10)
In Java, the array is initialized with the default value of the type. For example, int default is 0. The default value for cells of an array of objects is null as the array cells only hold references to the memory slot contains the object itself. The default reference points to null. In order to fill it with another default value, you have to call Arrays.fill() as you mentioned.
Object[] arr=new Object[2];
Arrays.fill(arr, new Object());
As far as I know there is no way of doing what you want with just plain java (that is to say there may be an external library I don't know about).
I would take the hit and loop over the array. Something like this should work:
myObject[] array = new myObject[5];
for (int i = 0; i < array.length; i++) {
array[i] = new myObject();
}
You could also shorten this using lambdas, like Cardano mentioned in his answer.

ArrayList of custom objects [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
I have a simple class with only one String field and I have ArrayList.
When I do for loop to add some elements to ArrayList something strange happeneds.
ArrayList<MyClass> list = new ArrayList<Myclass>();
MyClass mc = new MyClass();
for(int i=0;i<someNumber;i++){
String s = new String(Integer.toString(i));
mc.setString(s);
list.add(mc);
}
After this, when I print my list, the string for every element from the list is same.
I understand that if I do list.add(new Myclass(s); works correctly but do I need to create a new instance of MyClass every time? If someNumber is large it takes too much memory. Thanks
You are re-adding the same element to the list. Try:
List<MyClass> list = new ArrayList<>(someNumber);
for(int i=0;i<someNumber;i++){
String s = new String(Integer.toString(i));
MyClass mc = new MyClass(); // create new object mc
mc.setString(s);
list.add(mc); // add the new object to the list
}
By the same object I mean the same pointer to the object, you must create new pointer (initialize new class) to add it to the list as separate instance. In this case you were setting different value in setString on the same object and multiplicating the object in the list.
You need to move the instantiation of the object mc inside the loop.
ArrayList<MyClass> list = new ArrayList<Myclass>();
for(int i=0;i<someNumber;i++){
MyClass mc = new MyClass();
String s = new String(Integer.toString(i));
mc.setString(s);
list.add(mc);
}

Array of classes which create instances

having Obj class which in his constructor has System.out.println("Hello world!") ;
I create an array of this class using - Obj[] objArray = new Obj[10] ; and nothing printed , means - no instance of Obj has been called . Is there any way to create such array ,but with instances , beyond create them in for loop ?
Well, since you want to know a way apart from using a for loop, you can do this: -
Obj[] objArray = {new Obj(), new Obj(), new Obj()};
What happens here is, you are initializing your array reference directly with array elements.
Now the type of actual array object is inferred from type of array reference on the LHS.
So, with that declaration, an array of size 3 (in the above case) is created, with each index in the array initialized with the instance of Obj class in the given order.
A better way that I would suggest is to use an ArrayList, in which case, you have double-braces initialization to initialize your List without for loop. And plus with an added advantage that you can anytime add new elements to it. As it dynamically increasing array.
List<Object> list = new ArrayList<Object>() {
{
add(new Obj());
add(new Obj());
add(new Obj());
}
}; // Note the semi-colon here.
list.add(new Obj()); // Add another element here.
Answers so far are good and helpful. I'm here just to remind you about
Obj[] objArray = new Obj[10];
Arrays.fill(objArray, new Obj());
Though, this will only assign one reference (to a new Obj()) to all of the elements of array.
When you do Obj[] objArray = new Obj[10] ;
You only create an array of references to point to the actual 'Obj` object.
But in your case the actual Obj object is never created.
for (int i = 0; i < objArray.length; i++) {
objArray[i] = new Obj();
}
Doing above will print the desired.
Finally do System.out.println(Arrays.deepToString(objArray)) to print toString() of all the Obj
Obj[] objArray = new Obj[10] ; just creates an array capable of holding 10 Objs. To place Objs into the array you need to either use Rohit's approach or write a simple for loop to initialize the array entries one at a time:
for (int i = 0; i < 10; i++) {
objArray[i] = new Obj();
}
Or, without a for loop:
int i = 0;
while (i < 10) {
objArray[i] = new Obj();
i++;
}

define an array which its elements are object in java

I want to define an array which its elements are object in java and i can use for ex this method:
public void add(Object elem);
Can anyone help me on this?
A literal object array is defined as any other array.
Object[] objects = new Object[10];
Though, more likely, you are looking for something like ArrayList
List<Object> object = new ArrayList<Object>();
Which will give you the .add functionality because it's a List.
Objecttype objects= new Objecttype [initial size]
Why you want to use arrays. go for ArrayList in which you don't bother to define your initial size also it provides its own add method
Defining an array of objects is just like defining any other array
Object[] objectList = new Object[MAX_LIMIT];
for(int i=0;i<objectList.length;i++){
objectList[i] = new ANY_DATA_TYPE();
}

Creating an array of objects in Java

I am new to Java and for the time created an array of objects in Java.
I have a class A for example -
A[] arr = new A[4];
But this is only creating pointers (references) to A and not 4 objects. Is this correct? I see that when I try to access functions/variables in the objects created I get a null pointer exception.
To be able to manipulate/access the objects I had to do this:
A[] arr = new A[4];
for (int i = 0; i < 4; i++) {
arr[i] = new A();
}
Is this correct or am I doing something wrong? If this is correct its really odd.
EDIT: I find this odd because in C++ you just say new A[4] and it creates the four objects.
This is correct.
A[] a = new A[4];
...creates 4 A references, similar to doing this:
A a1;
A a2;
A a3;
A a4;
Now you couldn't do a1.someMethod() without allocating a1 like this:
a1 = new A();
Similarly, with the array you need to do this:
a[0] = new A();
...before using it.
This is correct. You can also do :
A[] a = new A[] { new A("args"), new A("other args"), .. };
This syntax can also be used to create and initialize an array anywhere, such as in a method argument:
someMethod( new A[] { new A("args"), new A("other args"), . . } )
Yes, it creates only references, which are set to their default value null. That is why you get a NullPointerException You need to create objects separately and assign the reference. There are 3 steps to create arrays in Java -
Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty.
Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions.
Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations.
Declaring Arrays In Java
This is how we declare a one-dimensional array in Java –
int[] array;
int array[];
Oracle recommends that you use the former syntax for declaring arrays.
Here are some other examples of legal declarations –
// One Dimensional Arrays
int[] intArray; // Good
double[] doubleArray;
// One Dimensional Arrays
byte byteArray[]; // Ugly!
long longArray[];
// Two Dimensional Arrays
int[][] int2DArray; // Good
double[][] double2DArray;
// Two Dimensional Arrays
byte[] byte2DArray[]; // Ugly
long[] long2DArray[];
And these are some examples of illegal declarations –
int[5] intArray; // Don't mention size!
double{} doubleArray; // Square Brackets please!
Instantiation
This is how we “instantiate”, or allocate memory for an array –
int[] array = new int[5];
When the JVM encounters the new keyword, it understands that it must allocate memory for something. And by specifying int[5], we mean that we want an array of ints, of size 5.
So, the JVM creates the memory and assigns the reference of the newly allocated memory to array which a “reference” of type int[]
Initialization
Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.
All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax –
int[] arr = {1, 2, 3, 4, 5};
Here, we don’t mention the size, because JVM can see that we are giving 5 values.
So, until we instantiate the references remain null. I hope my answer has helped you..! :)
Source - Arrays in Java
You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:
A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
limit(4) sets amount of elements which stream will generate
toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.
For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.
Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:
public class MainClass
{
public static void main(String args[])
{
System.out.println("Hello, World!");
//step1 : first create array of 10 elements that holds object addresses.
Emp[] employees = new Emp[10];
//step2 : now create objects in a loop.
for(int i=0; i<employees.length; i++){
employees[i] = new Emp(i+1);//this will call constructor.
}
}
}
class Emp{
int eno;
public Emp(int no){
eno = no;
System.out.println("emp constructor called..eno is.."+eno);
}
}
The genaral form to declare a new array in java is as follows:
type arrayName[] = new type[numberOfElements];
Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).
Lets initialize an array to store the salaries of all employees in a small company of 5 people:
int salaries[] = new int[5];
The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.
Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:
int salaries[] = {50000, 75340, 110500, 98270, 39400};
Or to do it at a later point like this:
salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;
More visual example of array creation:
To learn more about Arrays, check out the guide.
Yes it is correct in Java there are several steps to make an array of objects:
Declaring and then Instantiating (Create memory to store '4' objects):
A[ ] arr = new A[4];
Initializing the Objects (In this case you can Initialize 4 objects of class A)
arr[0] = new A();
arr[1] = new A();
arr[2] = new A();
arr[3] = new A();
or
for( int i=0; i<4; i++ )
arr[i] = new A();
Now you can start calling existing methods from the objects you just made etc.
For example:
int x = arr[1].getNumber();
or
arr[1].setNumber(x);
For generic class it is necessary to create a wrapper class.
For Example:
Set<String>[] sets = new HashSet<>[10]
results in: "Cannot create a generic array"
Use instead:
class SetOfS{public Set<String> set = new HashSet<>();}
SetOfS[] sets = new SetOfS[10];
Suppose the class A is such:
class A{
int rollno;
int DOB;
}
and you want to create an array of the objects for the class A. So you do like this,
A[] arr = new A[4]; //Statement 1
for (int i = 0; i < 4; i++) {
arr[i] = new A(); //Statement 2
}
which is absolutely correct.
Here A is the class and in Statement 1 Class A is a datatype of the array. When this statement gets executed because of the new keyword an object is created and dynamically memory is allocated to it which will be equal to the space required for the 4 blocks of datatype A i.e, ( for one block in the array space required is 8 bytes (4+4), I am assuming int takes 4 bytes of space. therefore total space allocated is 4*4 bytes for the array ).
Then the reference of the object is given to the arr variable. Here important point to note is that Statement 1 has nothing to do with creating an object for class A ,no object is created for this class it is only used as a datatype which gives the size of the class A required for the memory allocation of the array.
Then when for loop is run and Statement 2 is executed JVM now allocates the memory for the Class A (i.e creates an object) and gives its reference to the arr[i]. Every time the loop is called an object is created and the reference of it is given to arr[i].
Thus, arr[0] which holds a space of 8 bytes is given the reference of the object of the Class A and everytime loop is run new object is created and reference is given to that object so that it can now access the data in that object .

Categories

Resources