Reputation: 37
I have 3 classes and I want to make an object in each of them to control the other
for example, I am asked to do:
Generates a model of a Candy with the specified number of candies.
I am going to do that in class B, but the Candy is in a seperate class
public Candy(String CompanyName, String ProducerName) throws TeamException{
This.CandyProducer = ProducerName;
This.CandyCompany = CompanyName;}
Now I know I can do:
Candy FirstCandy = new Candy(KitKat, Stephen);
to create an object in the class Candy.
But what I want is to have 5 objects of the class Candy.
I tried doing:
List<Candy> CandyModel = ArrayList<Candy>(numOfCandies);
but it did not work, because I can't assign the "CompanyName", and "ProducerName" for any of the candies in the ArrayList.
Any tips ?
Upvotes: 0
Views: 3046
Reputation: 742
You can use a loop to add newly created Candy
objects to your list
for (int i = 0; i < numOfCandies; i++) {
CandyModel.add(new Candy("Company" + i, "Producer" + i));
}
The ArrayList
constructor creates an empty list which you need to populate with objects. The parameter in the constructor is an "expected size" or "initial internal capacity" that the list will grow to but it won't make any logical difference.
Upvotes: 1
Reputation: 138
also u miss new keyword while creating array list there..
Candy FirstCandy = new Candy("KitKat", "Stephen");
Candy SecondCandy = new Candy("KitKat", "Stephen");
Candy ThirdCandy = new Candy("KitKat", "Stephen");
List<Candy> CandyModel =new ArrayList<Candy>();
CandyModel.add(FirstCandy);
CandyModel.add(SecondCandy);
CandyModel.add(ThirdCandy);
an you can iterate it using listIterator or iterator somthing like this
ListIterator<Candy> itr=CandyModel.listIterator();
System.out.println("traversing elements in forward direction...");
while(itr.hasNext()){
System.out.println(itr.next());
}
Upvotes: 0