fornax666 fornax666 - 1 year ago 131
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: " + " 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?



public class Card {

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

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

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

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

Answer Source

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 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(…)
System.out.println("Name: " + + …)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download