You need to create objects, make a list and loop through. Can I do this:

MyClass obj = new MyClass(); MyClass obj2 = new MyClass(); ArrayList objList = new ArrayList(); objList.add(obj); objList.add(obj2); for (int i = 0; i < objList.size(); i++) { //Делаем работу } 

Or so:

 ArrayList objList = new ArrayList(); objList.add(new MyClass()); objList.add(new MyClass()); for (int i = 0; i < objList.size(); i++) { //Делаем работу } 

Is it possible to do that? What is added to the list in the first case: new objects or a link to already created objects?

    2 answers 2

    The new operator in Java returns a reference to the created object. Consider what happens in both cases.

    1. obj variable obj type MyClass you assign a reference to an object of type MyClass .

    MyClass obj = new MyClass();

    The object itself is created in dynamic memory, and the operator new returns a reference to this memory. So even when you use the obj variable, you manipulate the object reference! And now, I think it is clear that this line of code:

    objList.add(obj);

    You add a link to an object, not the object itself! Now the program has 2 object references: obj and objList .

    1. As I said, the new operator returns a link to the created object. Therefore, you can write this:

    objList.add(new MyClass());

    In this case, the created object will have one link and you can get it like this (let's say this is the first element in objList ):

    objList.get(0);

    What is the difference?

    If you plan to use the created object in the future, use the first option. On the contrary, if you are sure that the reference to the object you have nothing to do - use the second method.

      Is it possible to do that?

      Can. Both options are equivalent.

      What is added to the list in the first case: new objects or a link to already created objects?

      Link to already created objects.