Reputation: 107
*The fill method is meant to be called from another class, which has a menu consisting of options, one of which is a fill option.
I am trying to add twenty six huntsingercard objects to an array list of huntsingercard objects outside of the constructor. Oddly enough, I can't seem to accomplish this without using the constructor to fill the array list. I've tried the same thing with arrays and it works just fine, but the fill() method fails to add values onto the list.
class huntsingerdeck
{
private ArrayList<huntsingercard> list = new ArrayList<huntsingercard>();
public huntsingerdeck()
{
}
public void fill()
{
for(int a=0; a<26; list.add(a++,new huntsingercard()));
}
What exactly am I missing here? I've also tried instantiating the list in the constructor, but that also messes with the array as well.
Upvotes: 0
Views: 813
Reputation: 22442
Basically your for loop syntax is incorrect, the last expression should be 0 to n arithmetic operations, not boolean (because add() returns boolean)
So, you need t change it as below (with a++ expression): Also, as you don't want to use a constructor, you can use instance initializer as shown below:
class huntsingerdeck
{
private ArrayList<huntsingercard> list = new ArrayList<huntsingercard>();
public huntsingerdeck()
{
}
{
fill();
}
public void fill()
{
for(int a=0; a<26; a++) {
list.add(new huntsingercard()));
}
}
for loop syntax:
for (initialization; termination; increment) {
statement(s)
}
You can refer here
Upvotes: 0
Reputation: 7905
You can achieve this with an instance initializer
public class HuntSingerDeck {
private ArrayList<HuntSingerCard> list = new ArrayList<HuntSingerCard>();
{
for(int a=0; a<26; a++) {
list.add(new HuntSingerCard()));
}
}
public HuntSingerDeck() {
//Array list is already initialised and filled at this point
}
}
Instance initializers will be fired before the constructor is called when creating a new instance. This means the arraylist will be filled before reaching the start of the constructor.
Upvotes: 1