开发者

Is an ArrayList automatically declared static in Java, if it is an instance variable?

开发者 https://www.devze.com 2022-12-29 11:07 出处:网络
I\'m trying to do something like this: private class aClass { private ArrayList<String> idProd; aClass(ArrayList<String> prd)

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 autom开发者_开发知识库atically declared static?


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.


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 :)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消