Suppose you have a java class called Chicken but the number of Chicken instances is not know before run time because it depends on user input. How do you make new instances of Chicken during run time, depending on user input?
2 Answers
If you need to dynamically create new objects and assign them to a variable, I would utilize a map with the key used to simulate naming a variable and the value as the newly created Chicken object: e.g.
new HashMap<nameOfVariable, Chicken>()
This will get you around not knowing the number or name of your instances at runtime. For example, if you were reading in a file from a user that was a list of named Chicken objects.
Comments
Here's how to make new instances of Chicken during run time, depending on user input :
import java.util.Scanner;
import java.util.Vector;
public class A
{
public static void main(String[] args)
{
System.out.println("Enter number of chikens :");
Scanner scanner = new Scanner(System.in);
int numberOfChukens = scanner.nextInt();
Vector chikenArray = new Vector<>();
for(int i=0;i<numberOfChukens;i++)
{
chikenArray.add(new Chiken());
}
}
}
1 Comment
JB Nizet
Please, don't suggest using Vector. It shouldn't be used anymore for 15 years. And use generic collections. They've been existing for 10 years, since Java 5.
List<Chicken>and then keep addingnew Chicken()to the list as needed.