views:

103

answers:

3

I'm trying to do something like this:

private class aClass
{
  private ArrayList<String> idProd;

  aClass(ArrayList<String> prd) 
  {
      this.idProd=new ArrayList<String>(prd);
  }

public ArrayList<String> getIdProd()
  {
      return this.idProd;

  }
}

So if I have multiple instances of ArrayLIst<String> (st1 ,st2 ,st3) and I want to make new objects of aClass:

{
 aClass obj1,obj2,obj3;
 obj1=new aClass(st1);
 obj2=new aClass(st2);
 obj3=new aClass(st3);
}

Will all of the aClass objects return st3 if I access the method getIdProd() for each of them(obj1..obj3)? Is an ArrayList as an instance variable automatically declared static?

+3  A: 

No, member variables are not automatically static unless you have declared them as such. I would suggest that you reformat your question and post additional context so as to make your question clearer. Most likely the results that you are getting differ from what you expect for a different reason than your question implies.

Michael Aaron Safyan
+1  A: 

You create a new arraylist in your class from an existing one, which adds all elements of the existing one into the new array list.

The elements however are the same, because the array list is not "deep cloned", which seems what you look for. You have to build an constructor which calles clone() on all elements and adds the clones to the new array list in your classes.

BTW: Use the code format feature to make your questions more readable. EDIT: Oh, you did it while I was posting this answer :)

Daniel
A: 

Data members are not automatically static, unless you declare them inside interfaces (not common)

Since you copy the array list in the constructor, and since the item type is immutable (String), the different instances of aClass work on completely different copies of ArrayList.

Eyal Schneider