I'm trying to make a list containing different objects.
List<Object> list = new ArrayList<Object>();
defObject defObj;
optObject optObj;
and defObject has just one property for a String.
public static class defObject
{
public static String defObj;
public defObject(String x)
{
setDefObj(x);
}
public static String getDefObj() {
return defObj;
}
public static void setDefObj(String defObj) {
defObject.defObj = defObj;
}
}
if I add multiple defObjects to the list and go through the list after I'm done adding the element they all contain the same string, which was of the last defObject added to the list.
I'm doing something like this to add the objects to the list:
if (whatever)
list.add(defObj = new defObject("x"));
else if(whatever)
list.add(defObj = new defObject("y"));
and the result is two defObjects with a string of "y"
Please help me figure out why the objects aren't being added correctly and the properties are all same as the last defObj added to the list.
The problem is defObj
is static
so all instances are sharing the same variable. Remove the word static
from everywhere in your class and everything will likely work as you expect.
The String defObj
variable is static, so it's always equal for all instances of defObject. Remove the "static
" before your method and attribute declaration and it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With