0

I'm trying to add objects to an ArrayList, but it seems that whenever I call the add method, the list is populated by only the last object that I add.

Here's how I add:

MyObject testObject1 = new MyObject();
testObject1.setType(0);
MyList.myList.add(testObject1);
MyObject testObject2 = new MyObject();
testObject2.setType(1);
MyList.myList.add(testObject2);

MyList is a class with a single ArrayList which is defined as follows:

public static ArrayList<MyObject> myList = new ArrayList<MyObject>();

MyObject is a class with some member variables and methods:

static int type;
public void setType(int inType) {
  type = inType;
}

I then list out the objects in MyList.myList as follows:

for (int i=0; i<MyList.myList.size(); i++) {
  Log.d(TAG, "Type is " + MyList.myList.get(i).getType());
}

It lists 2 objects, but the type is always 1.

What's up?

Thanks.

2 Answers 2

3

because setType is static, which isn't associated with Object's state

MyObject.setType = 1;

remove static keyword from setType 's delcaration in MyObject class and set its value per instance


See

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I made a typo in the original posted code. I didn't actually call MyObject.setType(), but called the instance's setType instead, i.e. testObject1.setType(0) and testObject2.setType(1)
post your setType method full body
Done. It's in the MyObject class.
its the same thing you are assigning value to static variable, which is not per object but per class loaded, so all the instances share values, please re read my answer
0
static int type;
public void setType(int inType) {
  type = inType;
}

You should not be setting a static variable from an instance method.

int type;
public void setType(int inType) {
  type = inType;
}

Changing as above will fix your issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.