0

i have a class with a constructor that returns objects. I'm adding these objects to a list but having trouble because every time i add a new element it replaces the previous ones with the current element that i am adding.

Here is the list and output:

    Objects a = new Objects("test1");
    Objects b = new Objects("test2");

    List<Objects> c = new ArrayList();

    c.add(a);
    c.add(b);
    System.out.println(c.get(0).getTest());
    System.out.println(c.get(1).getTest());

Here is the output:

test2
test2

Here is the class creating/returning the objects:

public class Objects
{
    public static String test;

    public Objects (String test)
    {
        this.test = test;
    }

      public String getTest()
      {
          return test;
      }
}
HashTables
  • 392
  • 2
  • 7
  • 22

5 Answers5

2

remove the static in Objects for class member test:

public class Objects
{
    public String test;

    public Objects (String test)
    {
        this.test = test;
    }

      public String getTest()
      {
          return test;
      }
}

then you will get the desired output:

Test1

Test2

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object.

nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

Static is the problem here. Remove Static and it will work fine. Using statics like this example is not a good practice, read here.

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

Change public static String test; as public String test;

The static keyword in Java means that the variable or function is shared between all instances of that class as it belongs to the type, not the actual objects themselves.

So if you have a variable: private static int i = 0; and you increment it (i++) in one instance, the change will be reflected in all instances. i will now be 1 in all instances.

And Read

Community
  • 1
  • 1
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
0
public static String test;

This is the problem. test is class level variable, so you simply modify it, instead of creating a new one. Also, usually you make the variable private, and provide getter and setter to for the variable. That is called encapsulation

OPK
  • 4,120
  • 6
  • 36
  • 66
0

Since you have declared test as static same variable will be used for all Objects instances. So its not overwriting the objects in the list . Its overwriting the value of test.

Solution :

Remove static modifier public String test;

Rahman
  • 3,755
  • 3
  • 26
  • 43