1

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?

2
  • Btw, it's good practice to use the interface (i.e., List) in variable and method declarations, and the specific implementation (ArrayList) only when creating a new concrete instance. See e.g. stackoverflow.com/questions/822768/… Commented May 9, 2010 at 8:13
  • 1
    there's absolutely nothing relevant about ArrayList in this context. You should divorce ArrayList from the question and try to understand the fundamentals of your confusion instead. Commented May 9, 2010 at 8:25

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.