Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A list of objects in Java [duplicate]

Tags:

java

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.

like image 309
Mitciv Avatar asked Dec 02 '22 07:12

Mitciv


2 Answers

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.

like image 146
Asaph Avatar answered Dec 29 '22 05:12

Asaph


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.

like image 25
Marc Müller Avatar answered Dec 29 '22 05:12

Marc Müller