简体   繁体   English

如果ArrayList是实例变量,是否在Java中自动将其声明为静态?

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

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: 因此,如果我有ArrayLIst<String> (st1,st2,st3)的多个实例,并且想要创建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)? 如果我为每个aClass对象(obj1..obj3)访问方法getIdProd(),所有aClass对象都会返回st3吗? Is an ArrayList as an instance variable automatically declared static? 是否将ArrayList作为实例变量自动声明为静态?

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. 您必须构建一个构造函数,该构造函数在所有元素上调用clone()并将克隆添加到类中的新数组列表中。

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. 由于您在构造函数中复制了数组列表,并且项类型是不可变的(字符串),因此,aClass的不同实例可以在完全不同的ArrayList副本上工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM