简体   繁体   中英

How to make an array of objects of undefined length of a class with parameterized constructor in JAVA?

Scanner sc=new Scanner(System.in);
System.out.println("Enter the number.");
int n=sc.nextInt();
PIDManager[] ob;
for (int j=0;j<n;j++)
{   
    ob[j]=new PIDManager("Thread Number "+(j+1));
}

Here PIDManager is a class, and the compiler shows an error that ob may not have been defined.

Use growable array like ArrayList if you dont know the size in advance like:

List<PIDManager> ob = new ArrayList<>();
..
ob.add(new PIDManager("Thread Number "+(j+1)));

and then add the elements to it with add method. If you know the size then you could define the array like:

PIDManager[] ob = new PIDManager[n];

You have to specify the size of an array in Java when you initialize it (arrays do not grow in Java). Use a collection like ArrayList or LinkedList instead.

Also, you haven't initialized your array at all.

PIDManager[] ob;

Should be (assuming you did know the size at the time).

PIDManager[] ob = new PIDManager[size];

There seems to be something wrong with the logic in the snippet though. Since you seem to actually need an array of size n judging from for (int j=0;j<n;j++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM