1

i have class in which i declare a static variable id

class id
{
  private static int id;
  public int getid()
 {
  return this.id
 }
public void setid(int id)
 {
    this.id=id;
 }
}

i have another class in which i create the object of this class and call these methods

class abc
{
    id obj=new id();
      int a=obj.getid();
    obj.setid(a+1);

}

now i am storing it to an static ArrayList in another class

class ser
{
  private static ArrayList<id>al=new ArrayList<id>();

  public static addid(id obj)
 {
   al.add(obj);
 }
}

now the problem is that it replaces the object every time i add the object to the list what is the error please help

Aaditya
  • 43
  • 6
  • Possible duplicate of [Static vs Instance Variables: Difference?](http://stackoverflow.com/questions/21204589/static-vs-instance-variables-difference) – Joe C Apr 02 '17 at 10:14
  • Yes please tell me how to do it with static variable declared.... – Aaditya Apr 02 '17 at 10:22

1 Answers1

0

All the objects id have the same value for the variable id because it is a static member of the class. So when you add several instances of the class id to the list, all instances have the same value for id. Are you sure you want the variable id to be static?

Markus
  • 1,141
  • 1
  • 9
  • 25