2174/array-of-objects
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.
Here is how you can create an array of 10 employee objects, with a parameterized constructor :
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); } }
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"), . . } )
It's defined in the Java language specification: The members ...READ MORE
int[] a = {1,2,3,4,5}; int[] b = Arrays.copyOf(a, ...READ MORE
We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE
Here is a simple way using an ArrayList: List<Integer> ...READ MORE
Yes; the Java Language Specification writes: In the Java ...READ MORE
You can use this method: String[] strs = ...READ MORE
public <T> T[] concatenate(T[] a, T[] b) ...READ MORE
Another workaround if you use apache commons-lang: int[] ...READ MORE
import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang.ArrayUtils; public class MinMaxValue { ...READ MORE
import java.util.List; import java.util.ArrayList; import java.util.Random; public class A ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.