List of objects in Java

I am trying to create a list containing different objects.

List<Object> list = new ArrayList<Object>(); defObject defObj; optObject optObj; 

and defObject has only one property per row.

  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 several defObjects to the list and go through the list after I finish adding the item, they all contain the same line that was from the last defObject added to the list.

I am doing something like this to add 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 the string "y"

Please help me understand why the objects are not being added correctly, and the properties are all the same as the last defObj added to the list.

+4
source share
4 answers

The defObj problem is static , so all instances use the same variable. Remove the word static from all sides of your class, and everything will work as you expect.

+12
source

The String defObj is static, so it is always equal for all defObject instances. Remove " static " before declaring the method and attribute, and it should work.

+3
source

Replace:

 public static class defObject { public static String defObj; ... 

FROM

 public static class defObject { public String defObj; .... 

Or even better for:

 public class DefObject { private String defObj; .... 

Using the static will make an attribute or method a class , which means that for all instances there will be only one.

Remove it from your code. Also, pay attention to Java by convention, the class name begins with an uppercase, and the opening bracket is on the same line.

+3
source

After removing static from public static String defObj; and to create private you will also need to remove static from your method signatures, since static methods cannot access instance variables from a static context, i.e. defObject.getDefObj() cannot access the defObj instance defObj , because the compiler cannot guarantee that it already exists - the instance was not created, and therefore there is no instance variable. This can only be done using the static properties when loading the class.

0
source

All Articles