fornax666 fornax666 - 23 days ago 8
Java Question

For loops, multiple object instantiation and adding the objects to an ArrayList problems

Having some trouble with a program I'm trying to write to imitate the card game 'Top Trumps', more specifically adding the Attributes of each Card to the ArrayList held by my class Card.

for (int i=1; i<5;i++)
{
int tempVal = rn.nextInt(10);
Card.attrbts.add(new Attribute ("Attribute "+i, tempVal));
System.out.println("Name: "+Attribute.name + " Value: " + tempVal); //debug
}


The program is supposed to randomly generate the value of each attribute and for simplicity I am just naming the each Attribute 'Attribute + i'.

The loop executes as expected for the most part, the value and names are generated fine as I can see from the debug statement, however, while this loop is adding elements to the ArrayList in my Card class it's using the same name and value for each element in the list, specifically the final iteration of my for loop (e.g. Attribute 4 and 6).

I was wondering if one of you could help explain to me why this is happening and how I'd go about fixing it?

Cheers

EDIT:

public class Card {

static ArrayList<Attribute> attrbts = new ArrayList<Attribute>();
String name;

public Card(String n, ArrayList<Attribute>attr)
{
this.name = n;
this.attrbts = attr;
}

public class Attribute {
static String name;
static int val;


public Attribute(String n, int v){
this.name = n;
this.val = v;
}

Answer

You are using static fields name and val. Static fields are shared by all objects of that class. Instead, you want each object/instantiation to have its own version.

For this, simply remove static.

public class Attribute {
    String name;
    int val;

…
}

(You should probably have got a warning in your Attribute constructor for accessing the static fields through a non-static reference).

There a plenty of resources on static fields. For instance have a look at Java Static vs Instance (thanks to Murat for pointing to this question).


Your debug print statement won't work, as you accessing the field in a static way Attribute.name. If you would want to access that field, you have to query the attribute object directly. For instance by saving it into a variable like this:

Attribute attr = new Attribute(…)
Card.attrbts.add(attr);
System.out.println("Name: " + attr.name + …)
Comments